Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my data.frame columns lists?

Tags:

dataframe

r

I have a data.frame

'data.frame':   4 obs. of  2 variables:
 $ name:List of 4
  ..$ : chr "a"
  ..$ : chr "b"
  ..$ : chr "c"
  ..$ : chr "d"
 $ tvd :List of 4
  ..$ : num 0.149
  ..$ : num 0.188
  ..$ : num 0.161
  ..$ : num 0.187

structure(list(name = list("a", "b", "c", 
    "d"), tvd = list(0.148831029536996, 0.187699857380692, 
    0.161428147003292, 0.18652668961466)), .Names = c("name", 
"tvd"), row.names = c(NA, -4L), class = "data.frame")

It appears that as.data.frame(lapply(z,unlist)) converts it to the usual

'data.frame':   4 obs. of  2 variables:
 $ name: Factor w/ 4 levels "a",..: 4 1 2 3
 $ tvd : num  0.149 0.188 0.161 0.187

However, I wonder if I could do better. I create my ugly data frame like this:

as.data.frame(do.call(rbind,lapply(my.list, function (m)
  list(name = ...,
       tvd = ...))))

I wonder if it is possible to modify this expressing so that it would produce the normal data table.

like image 995
sds Avatar asked Sep 30 '22 17:09

sds


1 Answers

I recommend doing

do.call(rbind,lapply(my.list, function (m)
  data.frame(name = ...,
       tvd = ...)))

rather than trying to convert a list of lists into a data.frame

like image 112
MrFlick Avatar answered Oct 03 '22 06:10

MrFlick