Ali
Ali

Reputation: 1080

Extract same index elements from a list

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

Upvotes: 2

Views: 125

Answers (3)

akrun
akrun

Reputation: 887971

We can use transpose with flatten

library(purrr)
d %>% 
    transpose %>%
     map(flatten_dbl)
#[[1]]
#[1]   1  11 111

#[[2]]
#[1]   2  22 222

#[[3]]
#[1]   3  33 333

Upvotes: 1

Sotos
Sotos

Reputation: 51612

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

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 102910

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)

Upvotes: 4

Related Questions