Subset a list (choose matching values for all components)

后端 未结 2 1103
滥情空心
滥情空心 2021-01-21 15:46

I try to read out certain elements from a list in a way, thats equivalent to df[, c(1,4,5)] in a data.frame.

> obj <- list(c(1:5)         


        
相关标签:
2条回答
  • 2021-01-21 16:18

    You should call lapply with a function which is run on every list entry:

    obj <- list(c(1:5), c(1:5))
    lapply(obj, function(x) x[c(1, 4, 5)])
    #[[1]]
    [1] 1 4 5
    
    [[2]]
    [1] 1 4 5
    
    0 讨论(0)
  • 2021-01-21 16:21

    EDi has a great answer, but you can do it by passing the [ function to lapply plus additional arguments:

    lapply(obj, '[', c(1, 4, 5))
    

    You can access this and the other "weird" functions in R by quoting them:

    ?"["
    
    0 讨论(0)
提交回复
热议问题