Skip to content
Prev 360658 / 398503 Next

R column assignment fails for lists

This is actually a bit subtle -- you need to carefully read the Help
pages to see what's happening. Here's the explanation to the best of
my understanding (corrections happily accepted if I've got it wrong!).

First, let's simplify:
a b.a b.b
1 1   a   c
2 2   b   d
[1] 3


So we ended up with a 3 column data.frame where it seems we should
only have two, with the second being a list with 2 components.

But that's not how it works. ?data.frame says:

"... data.frame converts each of its arguments to a data frame by
calling as.data.frame(optional = TRUE) "

and ?as.data.frame says:

"If a list is supplied, each element is converted to a column in the
data frame."

Hence when as.data.frame() is called on the second column, a 2 element
list, it converts it into a 2 column data frame (of 2 rows each) thus
giving 3 columns in all in the data frame, yielding the error you saw.

Something like this is what also happens in your assignment, I assume.
Jim's solution assigned a 1 element list which yielded what you wanted
when as.data.frame converted it into a single column.

I think....

Cheers,
Bert




Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Tue, May 3, 2016 at 6:48 PM, David Winsemius <dwinsemius at comcast.net> wrote: