Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested named list to data frame

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?

like image 819
Apricot Avatar asked Apr 24 '26 22:04

Apricot


1 Answers

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))
like image 168
A5C1D2H2I1M1N2O1R2T1 Avatar answered Apr 27 '26 15:04

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!