[R] problem with rbind on data.frames that contain data.frames

Allan Engelhardt allane at cybaea.com
Wed Jun 30 22:55:28 CEST 2010


On 30/06/10 20:46, Michael Lachmann wrote:
> It took me some time to find this bug in my code. Is this a feature of 
> R? Am I doing something wrong?
>
> > a=data.frame(x=1:10,y=1:10)
> > b=data.frame(x=11:20,y=11:20)
> > z=data.frame(1:10,11:20)
>
> > a$z=z
You are (kind of) assigning *two* columns from the data frame "z" to the 
name 'z' in "a" which is probably not going to work as you expect.  R 
tries to be clever which may or may not be a Good Thing.  Try

a$z1 <- z[,1]
a$z2 <- z[,2]

or equivalent to keep the names straight.

As you have it, a$z is a data.frame, not a column, so you'd need a$z[,1] 
to get the 1:10 back from the original assignment of z.

The default printing of a does not help: always check using str:

 > str(a)
'data.frame':    10 obs. of  3 variables:
  $ x: int  1 2 3 4 5 6 7 8 9 10
  $ y: int  1 2 3 4 5 6 7 8 9 10
  $ z:'data.frame':    10 obs. of  2 variables:
   ..$ X1.10 : int  1 2 3 4 5 6 7 8 9 10
   ..$ X11.20: int  11 12 13 14 15 16 17 18 19 20


Hope this helps a little.

Allan



More information about the R-help mailing list