2

Supposing an example in R where we use the lapply function within a same function to create an one-level list:

lapply(1:5, function(x)
{
  r <- sample(4,1)

  i<-lapply(1:r, function (y)
  {
    matrix(rep(1*x*y,3))
  })
  i
})

The given result is a two-level list (list of lists) like this one:

[[1]]
[[1]][[1]]
     [,1]
[1,]    1
[2,]    1
[3,]    1


[[2]]
[[2]][[1]]
     [,1]
[1,]    2
[2,]    2
[3,]    2

[[2]][[2]]
     [,1]
[1,]    4
[2,]    4
[3,]    4

[[2]][[3]]
     [,1]
[1,]    6
[2,]    6
[3,]    6

[[2]][[4]]
     [,1]
[1,]    8
[2,]    8
[3,]    8


[[3]]
[[3]][[1]]
     [,1]
[1,]    3
[2,]    3
[3,]    3

[[3]][[2]]
     [,1]
[1,]    6
[2,]    6
[3,]    6


# ...

Preserving both lapply functions (or similar ones) and matrices with equal dimensions, how we could get an one-level list thus?

[[1]]
     [,1]
[1,]    1
[2,]    1
[3,]    1

[[2]]
     [,1]
[1,]    2
[2,]    2
[3,]    2

[[3]]
     [,1]
[1,]    4
[2,]    4
[3,]    4

# ...
3
  • lapply always returns a list. (That's what the l in the name stands for.) Use sapply instead to simplify. Commented Jan 10, 2018 at 17:12
  • 1
    If j is the object returned by your code, you may try unlist(j,recursive=FALSE). Commented Jan 10, 2018 at 17:17
  • @Gregor, your suggestion doen't keep matrices with the same dimensions. Commented Jan 10, 2018 at 18:19

2 Answers 2

2

Replace the second lapply with sapply and include the argument simplify = TRUE

Sign up to request clarification or add additional context in comments.

3 Comments

simplify = TRUE is the default for sapply, you don't need to include it. And to make this a better answer you should show the full code. (I'm not sure this actually duplicates OP's desired output).
I think that pushes all those nested 1-column matrices in to a wider matrix. I think OP wanted to keep the matrices separate, but just reducing the nesting layers.
That change doesn't preserve the dimensions of the matrices, like @wibeasley said.
1

I was curious how purrr can best accommodate matrices inside a list. The concluding flatten() line is the equivalent of @nicola's suggestion to use unlist(., recursive=F).

library(magrittr)
purrr::map(1:5, function(x) {
  r <- sample(4,1)

  purrr::map(1:r, function(y) {
    matrix(rep(1*x*y,3))
  }) 
}) %>% 
purrr::flatten() #This line is the equivalent of nicola's `unlist()`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.