简体   繁体   中英

Transform a matrix of lists into a data.frame

I need to transform a (large) matrix of lists into a data frame.

Example:

m <-matrix(list(c(1,1,1),c(2,2),c("a","a","a"),c("b","c")), nrow = 2, ncol = 2)
> m
     [,1]      [,2]       
[1,] Numeric,3 Character,3
[2,] Numeric,2 Character,2

Desiderata:

test <- data.frame(x=c(1,1,1,2,2),
                   y=c("a","a","a","b","c"))
> test
  x y
1 1 a
2 1 a
3 1 a
4 2 b
5 2 c

The elements are list . We may unlist by looping over the columns with apply and unlist the list elements

type.convert(as.data.frame(apply(m, 2, unlist)), as.is = TRUE)

-output

   V1 V2
1  1  a
2  1  a
3  1  a
4  2  b
5  2  c

Or instead of apply (which returns a matrix and matrix can only have a single type - characters have precedence over numeric type, thus the whole matrix is character and therefore we used type.convert to automatically convert the type), split by col ( asplit ), loop over with the columns with lapply , unlist and convert to data.frame

data.frame(setNames(lapply(asplit(m, 2), unlist), c("x", "y")))
  x y
1 1 a
2 1 a
3 1 a
4 2 b
5 2 c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM