1

This post is similar to my other post

Let's say if I have 4 matrices:

x1 <- matrix(1:9, nrow = 3)
x2 <- matrix(2:10, nrow = 3)
x3 <- matrix(3:11, nrow = 3)
x4 <- matrix(4:12, nrow = 3)

And I want to put them into a list() in a way like this:

[[1]]
[[1]][[1]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

[[1]][[2]]
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10


[[2]]
[[2]][[1]]
     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    4    7   10
[3,]    5    8   11


[[3]]
[[3]][[1]]
     [,1] [,2] [,3]
[1,]    4    7   10
[2,]    5    8   11
[3,]    6    9   12

Given that I have this list() to define which element in x to list in each element in the list:

> list <- list(c(1,2),3,4)

[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

Is there a way to write this list in a more dynamic way? Currently, I'm using this

x <- list(list(x1,x2),list(x3),list(x4))

I have tried using the below codes but they don't work:

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",list[[p]]))))
}

and

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",l))))
}
debster
  • 333
  • 2
  • 10

1 Answers1

1

You complicated too much, there is no need for a for loop and a lapply loop, the latter is enough to get the result.
Also, I have changed the name of the index vector list to ilist, since list already is a base R function.

ilist <- list(c(1,2),3,4)

mat <- ls(pattern = "x\\d+$", envir = .GlobalEnv)
x <- lapply(ilist, function(i) mget(mat[i], envir = .GlobalEnv))

The output is a list of named members, the names being the character strings "x*" in mat. To have a list of unnamed lists,

x <- lapply(ilist, function(i) unname(mget(mat[i], envir = .GlobalEnv)))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66