Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dataframe from list of lists but each element a column

I would like to create a dataframe from a list of lists where the resulting dataframe has a column for each element and the rows are the individual. It is hard to explain so I will try and produce an example to work on.

Lets say my list is as follows:

myList <- list(
  list(L=c(1,2,3),a=c(1,2,3),b=c(1,2,3)),
  list(L=c(4,5,6),a=c(4,5,6),b=c(4,5,6)),
  list(L=c(7,8,9),a=c(7,8,9),b=c(7,8,9)))

The resulting dataframe would like this:

df <- data.frame(ind = c(1,2,3),
  L.1 = c(1,4,7),L.2 = c(2,5,8), L.3 = c(3,6,9),
  a.1 = c(1,4,7),a.2 = c(2,5,8), a.3 = c(3,6,9),
  b.1 = c(1,4,7),b.2 = c(2,5,8), b.3 = c(3,6,9))

I have tried using

data.frame(do.call(rbind, myList))

df <- bind_rows(myList, .id="column_label")

but these produce three rows per individual not the desired output.

I also tried using: df <- bind_cols(myList) but this divides the columns to each list.

Any idea how to go about this?

Thanks, Eve

like image 361
QPaps Avatar asked Dec 23 '22 19:12

QPaps


1 Answers

If the names are always a match one-by-one, you can simply do,

do.call(rbind, lapply(myList, unlist))
#     L1 L2 L3 a1 a2 a3 b1 b2 b3
#[1,]  1  2  3  1  2  3  1  2  3
#[2,]  4  5  6  4  5  6  4  5  6
#[3,]  7  8  9  7  8  9  7  8  9
like image 133
Sotos Avatar answered Feb 22 '23 23:02

Sotos