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)
If you have the same length for each element in your list , in this case 3, then you can also do,
split.default(unlist(d), rep(seq(3), 3))
#$`1`
#[1] 1 11 111
#$`2`
#[1] 2 22 222
#$`3`
#[1] 3 33 333
Where the 3 can be obtained by unique(lengths(d))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With