Re: [R] Questions about cbind

From: Marc Schwartz <MSchwartz_at_mn.rr.com>
Date: Wed 04 Jan 2006 - 16:49:36 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Jan 04 16:58:13 2006

This archive was generated by hypermail 2.1.8 : Wed 04 Jan 2006 - 19:37:50 EST