Nested named list to data frame

2019-02-24 21:36发布

I have the following named list output from a analysis. The reproducible code is as follows:

list(structure(c(-213.555409754509, -212.033637890131, -212.029474755074, 
-211.320398316741, -211.158815833294, -210.470525157849), .Names = c("wasn", 
"chappal", "mummyji", "kmph", "flung", "movie")), structure(c(-220.119433774144, 
-219.186901747536, -218.743319709963, -218.088361753899, -217.338920075687, 
-217.186050877079), .Names = c("crazy", "wired", "skanndtyagi", 
"andr", "unveiled", "contraption")))

I want to convert this to a data frame. I have tried unlist to data frame options using reshape2, dplyr and other solutions given for converting a list to a data frame but without much success. The output that I am looking for is something like this:

  Col1        Val1      Col2          Val2
1 wasn      -213.55     crazy         -220.11
2 chappal   -212.03     wired         -219.18
3 mummyji   -212.02     skanndtyagi   -218.74

so on and so forth. The actual out put has multiple columns with paired values and runs into many rows. I have tried the following codes already:

do.call(rbind, lapply(df, data.frame, stringsAsFactors = TRUE)) 

works partially provides all the character values in a column and numeric values in the second.

data.frame(Reduce(rbind, df))

didn't work - provides the names in the first list and numbers from both the lists as tow different rows

colNames <- unique(unlist(lapply(df, names)))
M <- matrix(0, nrow = length(df), ncol = length(colNames), 
        dimnames = list(names(df), colNames))
matches <- lapply(df, function(x) match(names(x), colNames))
M[cbind(rep(sequence(nrow(M)), sapply(matches, length)),
    unlist(matches))] <- unlist(df)
M

didn't work correctly.

Can someone help?

2条回答
ら.Afraid
2楼-- · 2019-02-24 22:08

Here's another way:

as.data.frame( c(col = lapply(x, names), val = lapply(x,unname)) )

How it works. lapply returns a list; two lists combined with c make another list; and a list is easily coerced to a data.frame, since the latter is just a list of vectors having the same length.

Better than coercing to a data.frame is just modifying its class, effectively telling the list "you're a data.frame now":

L = c(col = lapply(x, names), val = lapply(x,unname))
library(data.table)
setDF(L)

The result doesn't need to be assigned anywhere with = or <- because L is modified "in place."

查看更多
够拽才男人
3楼-- · 2019-02-24 22:16

Since the list elements are all of the same length, you should be able to stack them and then combine them by columns.

Try:

do.call(cbind, lapply(myList, stack))
查看更多
登录 后发表回答