【问题标题】:R: Select rows by value and always include previous rowR:按值选择行并始终包括前一行
【发布时间】:2022-07-19 23:53:29
【问题描述】:

我正在尝试将数据框子集到某个列值为“13”的所有行,但我希望包含“13”行之前的所有行,无论该列中的值如何.

我不希望某行在特定列中位于具有“13”的行之前,但本身也具有值“13”时被包含两次。

这是一个示例数据框和解决方案,其中条件(将行子集到时间 = 13 和 (time=13)-1 的行,不重复)

ID  speed   dist    time
A   4        12     4
B   7        10     8
C   7        18     13
C   8        4      5
A   5        6      13
D   6        2      13
E   7        2      9

Becomes

ID  speed   dist    time
B   7       10      8
C   7       18      13
C   8       4       5
A   5       6       13
D   6       2       13

【问题讨论】:

    标签: r dataframe conditional-statements subset


    【解决方案1】:

    使用which 创建一个“时间”值为 13 的位置索引,然后从索引中减去 1 并将两者连接到子集

    i1 <- which(df1$time == 13) 
    ind <- sort(unique(i1 - rep(c(1, 0), each = length(i1))))
    ind <- ind[ind >0]
    df1[ind,]
    

    -输出

      ID speed dist time
    2  B     7   10    8
    3  C     7   18   13
    4  C     8    4    5
    5  A     5    6   13
    6  D     6    2   13
    

    数据

    df1 <- structure(list(ID = c("A", "B", "C", "C", "A", "D", "E"), speed = c(4L, 
    7L, 7L, 8L, 5L, 6L, 7L), dist = c(12L, 10L, 18L, 4L, 6L, 2L, 
    2L), time = c(4L, 8L, 13L, 5L, 13L, 13L, 9L)), 
    class = "data.frame", row.names = c(NA, 
    -7L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2021-10-09
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      相关资源
      最近更新 更多