【问题标题】:dplyr: how to include specific rows based on their position in filter function?dplyr:如何根据它们在过滤器函数中的位置包含特定行?
【发布时间】:2021-05-22 13:54:59
【问题描述】:

我想根据以下条件在 R 中选择我的数据的子样本: t1(组的第一行) - t1(组的第 i 行) >= 2.

虚拟数据:

id <- c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2)

t1 <- c(4,3,3,2,2,2,1,1,8,8,7,7,7,6,3)

df <- data.frame(id, t1)

具体来说,我的预期输出是:

id <- c(1,1,1,1,1,2,2)
t1 <- c(2,2,2,1,1,6,3)
df2 <- data.frame(id, t1)

我正在尝试使用dplyrgroup_by()filter() 找到解决方案,但我找不到包含每个组第一行索引的方法。 我试过了:

df %>% group_by(id)%>% filter(lag(t1)-t1 >= 2)

但这不是我想要的,也许是使用row_number() 的东西?

【问题讨论】:

    标签: r filter dplyr group-by


    【解决方案1】:

    我认为您不需要 lag,但 first 应该可以帮助您

    > df %>%
    +   group_by(id) %>%
    +   filter(first(t1) - t1 >= 2)
    # A tibble: 7 x 2
    # Groups:   id [2]
         id    t1
      <dbl> <dbl>
    1     1     2
    2     1     2
    3     1     2
    4     1     1
    5     1     1
    6     2     6
    7     2     3
    

    data.table 选项

    > setDT(df)[, .SD[first(t1) - t1 >= 2], id]
       id t1
    1:  1  2
    2:  1  2
    3:  1  2
    4:  1  1
    5:  1  1
    6:  2  6
    7:  2  3
    

    使用subset + ave 的基本 R 选项

    > subset(
    +   df,
    +   ave(t1, id, FUN = function(x) x[1]) - t1 >= 2
    + )
       id t1
    4   1  2
    5   1  2
    6   1  2
    7   1  1
    8   1  1
    14  2  6
    15  2  3
    

    【讨论】:

      【解决方案2】:

      base R,我们也可以这样做

      subset(df, (t1[!duplicated(id)][id] -t1) >= 2)
      

      -输出

      #   id t1
      #4   1  2
      #5   1  2
      #6   1  2
      #7   1  1
      #8   1  1
      #14  2  6
      #15  2  3
      

      【讨论】:

        猜你喜欢
        • 2016-03-30
        • 2020-04-28
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 2019-09-03
        • 2016-06-21
        相关资源
        最近更新 更多