首页 文章

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

提问于
浏览
1

鉴于这种

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 回答

  • 3

    这将返回一个适合从列表中选择项目的逻辑向量 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
    
  • 1
    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
    

相关问题