Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract same index elements from a list

Tags:

list

r

apply

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
like image 800
Ali Avatar asked Feb 20 '26 03:02

Ali


2 Answers

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)
like image 167
ThomasIsCoding Avatar answered Feb 22 '26 21:02

ThomasIsCoding


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

like image 31
Sotos Avatar answered Feb 22 '26 21:02

Sotos