user85727
user85727

Reputation: 173

Using lag() in dplyr doesnt work as expected

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?

Upvotes: 3

Views: 355

Answers (2)

user2100721
user2100721

Reputation: 3587

Another way by using if_else function of dplyr package

df %>% group_by(col1)  %>% mutate(FLAG=if_else(col2==44 & lead(col2,1)<44,TRUE,FALSE,missing = FALSE))
# Source: local data frame [15 x 3]
# Groups: col1 [3]
# 
# 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 FALSE
# 11     3     1 FALSE
# 12     3     2 FALSE
# 13     3    44  TRUE
# 14     3     1 FALSE
# 15     3    44 FALSE

Upvotes: 1

erc
erc

Reputation: 10123

You can include the condition that lead(col2) may not be NA.

df %>% 
  group_by(col1)  %>% 
  mutate(FLAG = (col2 == 44 & lead(col2, 1) < 44 & !is.na(lead(col2, 1))))

Source: local data frame [15 x 3]
Groups: col1 [3]

    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 FALSE
11     3     1 FALSE
12     3     2 FALSE
13     3    44  TRUE
14     3     1 FALSE
15     3    44 FALSE

Upvotes: 1

Related Questions