4

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

2 回答 2

4

排除filter(hp <= lag(hp))行 where lag(hp)is NA。您可以改为过滤该不等式for lag(hp)就像每个组的顶部行的情况一样。

我包括prev = lag(hp)为滞后创建一个独立变量,只是为了清晰和调试。

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 
于 2018-04-25T19:47:38.783 回答
3

由于OP打算使用<=(小于或等于)以前的值,因此使用lagwithdefault = +Inf就足够了。

此外,不需要在链中单独arrange调用,因为提供了 select 选项。dplyrlagorder_by

因此,解可以写成:

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
于 2018-04-25T22:11:31.823 回答