基于dplyr::lag()的dplyr::filter(),不会丢失第一个值
基于lag()函数筛选数据集时,会丢失每个组中的第一行(因为这些行没有lag值)。我如何避免这种情况,以便在没有任何滞后值的情况下保留第一行基于dplyr::lag()的dplyr::filter(),不会丢失第一个值,r,dplyr,lag,lead,R,Dplyr,Lag,Lead,基于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"
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))
ds%
组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别
排列(-mpg)%>%
过滤器(hp有过滤器(hp%
组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别
排列(-mpg)%>%
突变(上一个=滞后(hp))%>%
过滤器(hp因为OP
打算使用%
组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别组别
filter(hplag(hp,default=hp[1])
?@joran,以这种方式操作默认参数是一个很好的解决方案,在等价性不足的情况下,可以更新为“filter(hp>lag(hp,default=hp[1]-1))。
library(tidyverse)
ds %>%
group_by(cyl) %>%
arrange(-mpg) %>%
mutate(prev = lag(hp)) %>%
filter(hp <= prev | is.na(prev))
# A tibble: 4 x 4
# Groups: cyl [2]
mpg cyl hp prev
<dbl> <dbl> <dbl> <dbl>
1 21.4 6. 110. NA
2 21.0 6. 110. 110.
3 21.0 6. 110. 110.
4 18.7 8. 175. NA
ds %>%
group_by(cyl) %>%
filter(hp <= lag(hp, default = +Inf, order_by = -mpg))
#Below result is in origianl order of the data.frame though lag was calculated
#in ordered value of mpg
# # A tibble: 4 x 3
# # Groups: cyl [2]
# mpg cyl hp
# <dbl> <dbl> <dbl>
# 1 21.0 6.00 110
# 2 21.0 6.00 110
# 3 21.4 6.00 110
# 4 18.7 8.00 175