sds
sds

Reputation: 60084

Why are my data.frame columns lists?

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.

Upvotes: 8

Views: 8961

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99391

It looks like you're just trying to tear down your original data then re-assemble it? If so, here are a few cool things to look at. Assume df is your data.

A data.frame is just a list in disguise. To see this, compare df[[1]] to df$name in your data. [[ is used for list indexing, as well as $. So we are actually viewing a list item when we use df$name on a data frame.

> is.data.frame(df)  # df is a data frame
# [1] TRUE
> is.list(df)        # and it's also a list
# [1] TRUE

> x <- as.list(df)   # as.list() can be more useful than unlist() sometimes
                     # take a look at x here, it's a bit long

> (y <- do.call(cbind, x))  # reassemble to matrix form
#     name        tvd      
# [1,] "a"   0.148831 
# [2,] "b"  0.1876999
# [3,] "c"  0.1614281
# [4,] "d"  0.1865267

> as.data.frame(y)          # back to df
#   name       tvd
# 1    a  0.148831
# 2    b 0.1876999
# 3    c 0.1614281
# 4    d 0.1865267

Upvotes: 3

MrFlick
MrFlick

Reputation: 206606

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

Upvotes: 2

Related Questions