This question is an extension of R list get first item of each element.
a <- c(1,2,3)
b <- c(11,22,33)
c <- c(111,222,333)
d <- list(a,b,c)
> sapply(d, function(x) x[1])
[1] 1 11 111
The code above, extracts the first element of each list. My question is how can I generalize this to obtain a list which extracts all the same index elements and stores them in a list.
My desired output:
[[1]]
[1] 1 11 111
[[2]]
[1] 2 22 222
[[3]]
[1] 3 33 333
The following may help
sapply(1:3, function(k) sapply(d, function(x) x[k]),simplify = F)
or
Map(function(k) sapply(d, function(x) x[k]), 1:3)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments