I have the following data frame:
col1<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
col2<-c(1,2,3,44,1,1,2,3,44,44,1,2,44,1,44)
df<-data.frame(col1,col2)
I am trying to group by col1 entries, and find, for each grouping of col1, values of col2 that are equal to 44 and followed immediately by a smaller entry (<44), and FLAG such entries in a new column.
However, this code doesnt seem to work:
df %>% group_by(col1) %>% mutate(FLAG=(col2==44 & lead(col2,1)<44))
col1 col2 FLAG
<dbl> <dbl> <lgl>
1 1 1 FALSE
2 1 2 FALSE
3 1 3 FALSE
4 1 44 TRUE
5 1 1 FALSE
6 2 1 FALSE
7 2 2 FALSE
8 2 3 FALSE
9 2 44 FALSE
10 2 44 TRUE
11 3 1 FALSE
12 3 2 FALSE
13 3 44 TRUE
14 3 1 FALSE
15 3 44 NA
Specifically, entry 10 should be FALSE, since it has no entry <44 in the same grouping directly following it. Any suggestions on how to write code that works more generally to do what I want?
dplyr
loaded?lead
andlag
functions that behave differently thandplyr
versions. My guess is you had masked thedplyr
versions with those from another package.