如何通过另一个向量对向量进行子集化?

时间:2016-01-27 00:33:56

标签: r subset

鉴于此

data <- list(a=c(1,3,5), b=c(3,4,7,4,8,6), c=c(3,4,8,3,4,8,0))
sample <- c(4,8)

有没有办法检索包含序列c(4,8)的列表成员?

在这种情况下,这将是data$bdata$c

2 个答案:

答案 0 :(得分:3)

data[grep(paste0(c("", sample, ""), collapse = "_"), 
      paste0("_", sapply(data, paste0, collapse = "_"), "_"))]
# $b
# [1] 3 4 7 4 8 6
# 
# $c
# [1] 3 4 8 3 4 8 0

答案 1 :(得分:1)

这将返回一个适合从列表中选择项目的逻辑向量 - data

sapply(data, function(x) any(
                              intersect( which( x==sample[1]), # check for first value
     # then see if any of those locations also have successive differences are the same as in the `sample` item.
                                         which( diff(x) == diff(sample) ))  ))

$a
[1] FALSE

$b
[1] TRUE

$c
[1] TRUE

插图:

 data[ sapply(data, function(x) any( intersect(  which( x==sample[1]), 
                                               which( diff(x) == diff(sample) )) ) )
     ]
#----------
$b
[1] 3 4 7 4 8 6

$c
[1] 3 4 8 3 4 8 0