0

Data.frames seem to keep the underlying structure of the data, which can be inconvenient at times. In particular, I have a data.frame constructed from two lists (combined using rbind). Because the underlying list structure is maintained, this means I can't (easily) pull a column vector from the data.frame and functions that are often run on column vectors don't work. Is there a way to convert the underlying structure of a data.frame to a more "predictable" format.

Here's a simple example:

df1 <- data.frame(a = 2:1, b = 4:3)           # "standard" data.frame
df2 <- data.frame(rbind(list(a = 2, b = 4),   # "sad" data.frame
                        list(a = 1, b = 3)))

A quick check of str(df1$a) and str(df2$a) show that the former is a vector and the latter a list. As such, this confounds some common things we might try to do with a data.frame, for example, trying to order the data.frame by a:

df1[order(df1$a), ]  # works fine
df2[order(df2$a), ]  # returns: Error in order(df2$a) : unimplemented
                     #          type 'list' in 'orderVector1'

I know I can work around these issues with unlist, e.g., df2[order(unlist(df2$a)), ], but I'd really like to be able to make df2 "act like" df1. Especially since it is likely, in my case, that someone else may end up using my code. Is there a simply way to accomplish this (without unlisting each column one after the other)?

  • 3
    I'm not sure why you are constructing `df2` like you are. It is a very unusual method. `data.frame(lapply(df2,unlist))` will get it back to "normal" in one fell swoop, but the better idea would be to not introduce the problem to start with. – thelatemail Jun 11 '14 at 03:30
  • @thelatemail Thanks! The actual code is appending the output of a function (which are lists) to a dynamically growing data.frame (it's sad in several ways). You're advice is well heeded, though, and I'll see if I can address the problem earlier. Nonetheless, I do think it's rather quirky of R to allow for data.frames that don't behave in the way you would expect (or perhaps just a quirk of my R education that I wasn't aware of it before). – user3728334 Jun 11 '14 at 03:53
  • i tried rbind.data.frame() for the "sad" data.frame. It works like df1 while one problem is that the row name is weird. – useR Jun 11 '14 at 04:16

0 Answers0