How to access list in a list by character name in a loop?

Viewed 77

I have a list X of three elements. Each element X[[i]] is a list of two – X1 and X2.

I want to construct a list X_new which would be a list of two elements X1 and X2, each element X_new[[i]] is a list of three.

This works perfectly fine:

X_new <- vector(mode = "list", length = 2)
X_new[[1]] <- lapply(X, function(x) x$X1)
X_new[[2]] <- lapply(X, function(x) x$X2)

But what if instead of 2 I have n? I tried this

X_new <- vector(mode = "list", length = n)
ind <- names(X[[1]])
for (i in 1:n) {
   X[[i]]  <- lapply(X, function(x) x$ind[i])
}

but it doesn't work, I just get null lists.

2 Answers

We can use transpose from purrr

library(purrr)
X_new <- transpose(X)

-output

X_new
#[[1]]
#[[1]][[1]]
#[1] "a"

#[[1]][[2]]
#[1] "a"

#[[1]][[3]]
#[1] "a"


#[[2]]
#[[2]][[1]]
#[1] "b"

#[[2]][[2]]
#[1] "b"

#[[2]][[3]]
#[1] "b"

Refer to this discussion for an answer. In short, you can use paste inside the [[]] list brackets.

Related