在 dplyr 中按组滞后列
Lag colum by group in dplyr
我有如下数据框 mydata
:
col1 col2
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
Y 想在 col1
的组内落后于 col2
,所以我的预期结果如下:
col1 col2
1 1 NA
2 1 1
3 1 2
4 2 NA
5 2 1
6 2 2
按照 [this answer][1] 的程序,我试试
with_lagged_col2 =
mydata %>% group_by(col1) %>% arrange(col1) %>%
mutate(laggy = dplyr::lag(col2, n = 1, default = NA))
而我实际得到的是
# A tibble: 6 x 3
# Groups: col1 [2]
col1 col2 laggy
<dbl> <dbl> <dbl>
1 1 1 NA
2 1 2 1
3 1 3 2
4 2 1 3
5 2 2 1
6 2 3 2
为什么 group_by
在这里被忽略了?
你不需要那个安排:
with_lagged_col2 =
mydata %>% group_by(col1) %>% # groups data by col1
mutate(laggy = dplyr::lag(col2, n = 1, default = NA)) # creates new lagged variable of col1, the missing value i.e. first row is NA
我有如下数据框 mydata
:
col1 col2
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
Y 想在 col1
的组内落后于 col2
,所以我的预期结果如下:
col1 col2
1 1 NA
2 1 1
3 1 2
4 2 NA
5 2 1
6 2 2
按照 [this answer][1] 的程序,我试试
with_lagged_col2 =
mydata %>% group_by(col1) %>% arrange(col1) %>%
mutate(laggy = dplyr::lag(col2, n = 1, default = NA))
而我实际得到的是
# A tibble: 6 x 3
# Groups: col1 [2]
col1 col2 laggy
<dbl> <dbl> <dbl>
1 1 1 NA
2 1 2 1
3 1 3 2
4 2 1 3
5 2 2 1
6 2 3 2
为什么 group_by
在这里被忽略了?
你不需要那个安排:
with_lagged_col2 =
mydata %>% group_by(col1) %>% # groups data by col1
mutate(laggy = dplyr::lag(col2, n = 1, default = NA)) # creates new lagged variable of col1, the missing value i.e. first row is NA