当我根据 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))