1

Consider a nested matrix of this form, of which each element is a vector, list, or dataframe:

m <- matrix(replicate(3, list(1:3)))
m
#     [,1]     
#[1,] integer,3
#[2,] integer,3
#[3,] integer,3

How does one "unnest" this matrix? i.e. get this output:

unnestFunction(m)
#[[1]]
#[1] 1 2 3
#
#[[2]]
#[1] 1 2 3
#
#[[3]]
#[1] 1 2 3
Maël
  • 45,206
  • 3
  • 29
  • 67

5 Answers5

3

Use c:

c(m)
#[[1]]
#[1] 1 2 3
#
#[[2]]
#[1] 1 2 3
#
#[[3]]
#[1] 1 2 3
Maël
  • 45,206
  • 3
  • 29
  • 67
3

The "just use c()" is one way. You can also remove the dimensions attribute:

dim(m) <- NULL

str(m)
#------------
List of 3
 $ : int [1:3] 1 2 3
 $ : int [1:3] 1 2 3
 $ : int [1:3] 1 2 3
IRTFM
  • 258,963
  • 21
  • 364
  • 487
2

A possible solution:

m[T]

#> [[1]]
#> [1] 1 2 3
#> 
#> [[2]]
#> [1] 1 2 3
#> 
#> [[3]]
#> [1] 1 2 3

Another possible solution:

lapply(m, identity)

#> [[1]]
#> [1] 1 2 3
#> 
#> [[2]]
#> [1] 1 2 3
#> 
#> [[3]]
#> [1] 1 2 3
PaulS
  • 21,159
  • 2
  • 9
  • 26
2

You can try

> m[,1]
[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 2 3
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

1) Try c

m <- matrix(replicate(3, list(1:3)))
c(m)

giving

[[1]]
[1] 1 2 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 2 3

2) Mucking with internal representations probably isn't a good idea but this does work as well:

structure(m, .Dim = NULL)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341