【问题标题】:R: filter/subset range of rows based on cells containing specific valueR:根据包含特定值的单元格过滤/子集范围的行
【发布时间】:2018-12-13 01:59:11
【问题描述】:

我最近收到了关于根据特定列中的开始和停止值/标识符设置行范围的响应 - 可以读取响应 here

我希望这一次能得到一些帮助是做同样的事情(即子集标识符的每个实例之间的所有行),除了有问题的标识符嵌入在一个句子中。因此标识符本身包含在具有其他文本的单元格中。

例子:

X1                      X2
'hello this is a test'   1
'identifier 1234'        2
'hello'                  3
'hello'                  4
'hello 1234'             5
'hello again'            6

假设我要查找子集的行的标识符是“1234”,我希望的输出将是 2、3、4、5。标识符永远不会出现超过两次,因此有明确的起点和终点。

我尝试过组合过滤器、grepl 和 between,但只设法过滤带有标识符的行,而不是标识符之间的行。

我希望这是有道理的!

【问题讨论】:

    标签: r subset rows


    【解决方案1】:

    因为只有一个 'identifier' 实例指定了 'start/stop',所以使用 grep 获取与模式匹配的行索引,获取 start 和 end 之间的序列 (:)并子集“X2”值

    i1 <- grep('1234', df1$X1)
    df1$X2[i1[1]:i1[2]]
    #[1] 2 3 4 5
    

    数据

    df1 <- structure(list(X1 = c("hello this is a test", "identifier 1234", 
    "hello", "hello", "hello 1234", "hello again"), X2 = 1:6), 
      class = "data.frame", row.names = c(NA, -6L))
    

    【讨论】:

    • 这简单而优雅 - 非常感谢@akrun
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多