Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Convert list with different number of rows to data.frame

Tags:

list

dataframe

r

I would like to change this list to a data.frame:

[[1]]


AA AB 
21  1 

[[2]]

AA AB 
19  4 

[[3]]

AA AB 
23  1 

[[4]]

AA AB BB 
15  3  6 

I tried "as.data.frame(r)", but I got the following error:

Error in data.frame(c(21L, 1L), c(19L, 4L), c(23L, 1L), c(15L, 3L, 6L),  : 
  arguments imply differing number of rows: 2, 3

How can I get something like:

   AA AB BB
V1 21  1
V2 19  4
V3 23  1
V4 15  3 6
like image 359
aspire57 Avatar asked Mar 22 '15 20:03

aspire57


People also ask

How do I turn a list into a DataFrame in R?

Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.

How do I turn a large list into a DataFrame in R?

First, create a large list. Then use the Map function on the list and convert it to dataframe using the as. data. frame function in R.


1 Answers

If the list elements are named vectors,

library(stringi)
res <- as.data.frame(t(stri_list2matrix(r)))
colnames(res) <- unique(unlist(sapply(r, names)))
res
#  AA AB   BB
#1 21  1 <NA>
#2 19  4 <NA>
#3 23  1 <NA>
#4 15  3    6

Or if the list elements are 'data.frame'

library(data.table)
rbindlist(r1, fill=TRUE)

data

r <- list(structure(c(21, 1), .Names = c("AA", "AB")), structure(c(19, 
 4), .Names = c("AA", "AB")), structure(c(23, 1), .Names = c("AA", 
"AB")), structure(c(15, 3, 6), .Names = c("AA", "AB", "BB")))

r1 <- lapply(r, as.data.frame.list)
like image 71
akrun Avatar answered Jan 14 '23 18:01

akrun