How to get the nth element of each item of a list, which is itself a vector of unknown length

后端 未结 3 1302
-上瘾入骨i
-上瘾入骨i 2021-01-02 06:08

If we have a list, and each item can have different length. For example:

l <- list(c(1, 2), c(3, 4,5), c(5), c(6,7))

(In order to be cl

相关标签:
3条回答
  • 2021-01-02 06:47

    data.table::transpose(l) will give you a list with vectors of all 1st elements, all 2nd elements, etc.

    l <- list(1:2, 3:4, 5:7, 8:10)
    b <- data.table::transpose(l)
    b
    # [[1]]
    # [1] 1 3 5 8
    # 
    # [[2]]
    # [1] 2 4 6 9
    # 
    # [[3]]
    # [1] NA NA  7 10
    

    If you don't want the NAs you can do lapply(b, function(x) x[!is.na(x)])

    0 讨论(0)
  • 2021-01-02 07:00
    # the source list 
    source_list <- list(c(1, 2), c(3, 4,5), c(5), c(6,7))
    
    # the index of the elements you want 
    k <- 1
    
    # the results character vector 
    x <- c()
    
    for (item in source_list) {
         x <- append(x, item[k])
       }
    
    print(x)
    [1] 1 3 5 6
    
    0 讨论(0)
  • 2021-01-02 07:08

    We can create a function using sapply

    fun1 <- function(lst, n){
             sapply(lst, `[`, n)
       }
    fun1(l, 1)
    #[1] 1 3 5 6
    
    fun1(l, 2)
    #[1]  2  4 NA  7
    
    0 讨论(0)
提交回复
热议问题