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

杀马特。学长 韩版系。学妹 提交于 2019-12-01 05:52:35

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

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)])

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!