有人能解释一下使用 dplyr
包得到这样的结果吗?
我有一个数据框 df
library(dplyr)
df = data_frame(
'id' = c(1,2,2,2,2,3,3,3,3),
'start' = c(881, 1611, 1611, 1642, 1764, 0, 0, 28, 59),
'end' = c(1089, 1819, 1819, 1850, 1972, 208, 208,236, 267))
那看起来像是:
# Source: local data frame [9 x 3]
#
# id start end
# (dbl) (dbl) (dbl)
# 1 1 881 1089
# 2 2 1611 1819
# 3 2 1611 1819
# 4 2 1642 1850
# 5 2 1764 1972
# 6 3 0 208
# 7 3 0 208
# 8 3 28 236
# 9 3 59 267
通过按id
分组并在结束列应用滞后,我期望每个id
都会有一个缺失值。
df %>%
group_by(id) %>%
mutate(end.prev = lag(end))
但我有
# Source: local data frame [9 x 4]
# Groups: id [3]
#
# id start end end.prev
# (dbl) (dbl) (dbl) (dbl)
# 1 1 881 1089 NA
# 2 2 1611 1819 NA
# 3 2 1611 1819 1819
# 4 2 1642 1850 1819
# 5 2 1764 1972 1850
# 6 3 0 208 NA
# 7 3 0 208 NA <- I don't understant this NA
# 8 3 28 236 NA <- Neither this one
# 9 3 59 267 NA <- nor this other
我正在使用cran中最新版本的dplyr 0.4.3(我的R版本为3.2.5)
http://stackoverflow.com/questions/37710520/r-differences-by-group-and-adding/37715856#37715856
时遇到了问题。如果我们在dplyr
中使用lag
,它会显示 NA。 - akrun