当我根据lag()函数过滤数据集时,每个组的第一行会丢失(因为这些行没有lag值)。如何避免这种情况,以便保留第一行,尽管它们没有任何lag值?
ds <-
structure(list(mpg = c(21, 21, 21.4, 18.7, 14.3, 16.4), cyl = c(6,
6, 6, 8, 8, 8), hp = c(110, 110, 110, 175, 245, 180)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("mpg",
"cyl", "hp"))
# example of filter based on lag that drops first rows
ds %>%
group_by(cyl) %>%
arrange(-mpg) %>%
filter(hp <= lag(hp))
lag(hp,default = hp[1])
? - joran