繁体   English   中英

使用dplyr过滤从一个变量到另一变量的所有行

[英]Using dplyr to filter all rows from one variable until another

我的数据如下所示:

data <- data.frame(
  value = runif(10)
  id = c("junk","start","1","2","end","morejunk","junk","start","4","end")
)

我想使用filter()id "start"id "end"提取所有内容。 问题是开始行和结束行之间的观察次数不同,因此我无法筛选每x行。 有没有一种方法可以我可以from = "start" until = "end"来指定使用filter()

您可以首先确定“开始”和“结束”的位置。 然后使用这些成对的索引来索引data.frame。 假设每次都有对应的开始和结束对。

set.seed(0L)
data <- data.frame(
    value = runif(10),
    id = c("junk","start","1","2","end","morejunk","junk","start","4","end")
)
idx <- which(data$id %in% c("start", "end"))
lapply(split(idx, ceiling(seq_along(idx)/2)), function(x) data[x[1]:x[2],])

您可以

  • 使用which来标识带有"start""end"行索引,
  • 每一个分别加减1,以不包括那些行,
  • 通过Map将这些序列传递给:
  • unlist列表可将列表简化为向量,并且
  • slice子集

离开

library(dplyr)
set.seed(47)

data <- data.frame(
    value = runif(10),
    id = c("junk","start","1","2","end","morejunk","junk","start","4","end")
)

data %>% slice(unlist(Map(`:`, 
                          which(.$id == 'start') + 1, 
                          which(.$id == 'end') - 1)))
#> # A tibble: 3 × 2
#>       value     id
#>       <dbl> <fctr>
#> 1 0.7615020      1
#> 2 0.8224916      2
#> 3 0.5433097      4

或在基地

data[unlist(Map(`:`, 
                which(data$id == 'start') + 1, 
                which(data$id == 'end') - 1)), ]
#>       value id
#> 3 0.7615020  1
#> 4 0.8224916  2
#> 9 0.5433097  4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM