[R] Questions about cbind

Marc Schwartz MSchwartz at mn.rr.com
Wed Jan 4 06:49:36 CET 2006


On Wed, 2006-01-04 at 13:28 +0800, Vincent Deng wrote:
> Dear R-helpers
> 
> I have a stupid question about cbind function. Suppose I have a
> dataframe like this
> Frame:
> A 10
> C 20
> B 40
> 
> and a numeric matrix like this
> Matrix:
> A 1
> B 2
> C 3
> 
> cbind(Frame[,2],Matrix[,1]) simply binds these two columns without
> checking the order, I mean, the result will be
> A 10 1
> B 20 2
> C 30 3
> 
> rather than
> A 10 1
> B 30 2
> C 20 3
> 
> So my problem is: Is there any solution for R to bind columns with
> correct order?
> 
> Many thanks

I presume that either the '40' in the first expression of Frame or the
'30's in the second and third outputs are typos?

See ?merge, which will perform SQL-like 'join' operations using a
primary key:

> Frame
  V1 V2
1  A 10
2  C 20
3  B 40


Note that despite the name, this is not a matrix, but also a data frame.
A matrix can only have one data type, while a data frame can have more
than one.

> Matrix
  V1 V2
1  A  1
2  B  2
3  C  3


> merge(Frame, Matrix, by = "V1")
  V1 V2.x V2.y
1  A   10    1
2  B   40    2
3  C   20    3


HTH,

Marc Schwartz




More information about the R-help mailing list