Home > front end >  How to convert a list into a dataframe in R
How to convert a list into a dataframe in R

Time:10-07

I have a list in R in which the objects have different lengths.

Is there any way to convert this list into a dataframe? Maybe adding zeros in the shorter length objects.

I would like to be able to display a, b and c as columns and the numbers on the rows.

this is a small example. Later I will have to apply it to a list of 84 objects, each of these will have a long and different length from each other.

enter image description here

prova <- list(a = c(c(1:5), c(2,NaN, 4, 6,7)), b = c(c(6:10), c(NaN ,NaN,  6,7)), 
c=c(c(11:15),c(NaN ,NaN, 7.8,8,5,6,3,NaN)))
Thank you!

CodePudding user response:

As the length of each element is different, we may need to append NA at the end to make the lengths same by assigning the length to the max length of the list element and then convert to data.frame

mx <- max(lengths(prova))
data.frame(lapply(prova, `length<-`, mx))

-output

     a   b    c
1    1   6 11.0
2    2   7 12.0
3    3   8 13.0
4    4   9 14.0
5    5  10 15.0
6    2 NaN  NaN
7  NaN NaN  NaN
8    4   6  7.8
9    6   7  8.0
10   7  NA  5.0
11  NA  NA  6.0
12  NA  NA  3.0
13  NA  NA  NaN

CodePudding user response:

other methods include:

do.call(rbind, data.table::transpose(prova))
      [,1] [,2] [,3]
 [1,]    1    6 11.0
 [2,]    2    7 12.0
 [3,]    3    8 13.0
 [4,]    4    9 14.0
 [5,]    5   10 15.0
 [6,]    2  NaN  NaN
 [7,]  NaN  NaN  NaN
 [8,]    4    6  7.8
 [9,]    6    7  8.0
[10,]    7   NA  5.0
[11,]   NA   NA  6.0
[12,]   NA   NA  3.0
[13,]   NA   NA  NaN

t(plyr::rbind.fill.matrix(sapply(prova, t)))
   [,1] [,2] [,3]
1     1    6 11.0
2     2    7 12.0
3     3    8 13.0
4     4    9 14.0
5     5   10 15.0
6     2  NaN  NaN
7   NaN  NaN  NaN
8     4    6  7.8
9     6    7  8.0
10    7   NA  5.0
11   NA   NA  6.0
12   NA   NA  3.0
13   NA   NA  NaN
  • Related