0

Data

> dput(veh)
structure(list(Time = c(138.6, 138.7, 138.8, 138.9, 139, 139.1, 
139.2, 139.3, 139.4, 139.5, 139.6, 139.7, 139.8, 139.9, 140, 
140.1, 140.2, 140.3, 140.4, 140.5, 140.6, 149.9, 150, 150.1, 
150.2)), .Names = "Time", row.names = c(NA, -25L), class = c("tbl_df", 
"tbl", "data.frame"))

Using ifelse() in mutate() produce wrong results:

I'm finding the difference in the Time variable. Wherever the difference is greater than 0.1, I'd like to label that as BIG. Following is what I tried:

library(dplyr)
veh %>%
mutate(diff_t = c(NA, diff(Time))) %>%
mutate(act = ifelse(diff_t>0.1, "BIG", "NA"))   

# A tibble: 25 × 3
    Time diff_t   act
   <dbl>  <dbl> <chr>
1  138.6     NA  <NA>
2  138.7    0.1    NA
3  138.8    0.1   BIG
4  138.9    0.1    NA
5  139.0    0.1    NA
6  139.1    0.1    NA
7  139.2    0.1    NA
8  139.3    0.1   BIG
9  139.4    0.1    NA
10 139.5    0.1    NA
# ... with 15 more rows  

Why is 0.1 labelled as BIG here?

Trying the same code on another dataset produces correct results:

foo <- data.frame(a = c(1:5, 8))
foo %>% 
mutate(diff_a = c(NA, diff(a))) %>% 
mutate(act = ifelse(diff_a>1, "BIG", "NA"))  

  a diff_a  act
1 1     NA <NA>
2 2      1   NA
3 3      1   NA
4 4      1   NA
5 5      1   NA
6 8      3  BIG 

What am I doing wrong in the veh dataset?

Jaap
  • 81,064
  • 34
  • 182
  • 193
umair durrani
  • 5,597
  • 8
  • 45
  • 85
  • If you take the difference and check it, they are not exactly 0.1 – akrun Apr 11 '17 at 15:37
  • 1
    We have some nice floating point numbers here. `sprintf("%0.20f", diff(veh$Time))` – Vlo Apr 11 '17 at 15:39
  • Probably a [floating point issue](http://stackoverflow.com/questions/21872854/floating-point-math-in-different-programming-languages) – Jaap Apr 11 '17 at 15:39

1 Answers1

1

The numbers are not exactly equal to 0.1. One option is to round it and try with ifelse

veh %>% 
    mutate(diff_t = round(c(NA, diff(Time)),2), 
           act = ifelse(diff_t >= 0.1 & !is.na(diff_t), "BIG", NA))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Oh! I didn't know that the differences could be a little greater (or less) than 0.1. Thanks for your answer and comments. – umair durrani Apr 11 '17 at 15:45