Re: [R] Combining Vectors

From: Marc Schwartz <MSchwartz_at_mn.rr.com>
Date: Wed 17 May 2006 - 23:32:34 EST

On Wed, 2006-05-17 at 14:58 +0200, Fanie Nel wrote:
> Hi, I'm a new R user, and struggeling with the basics (...sigh)
>
> I would like to combine 2 vectors :
>
> d1:
>
> "S1" "S2" "S3" "S4"
> 1 3 5 6
>
>
> and
>
>
> d2:
>
> "S1" "S3" "S5"
> 3 3 2
>
> to give a result:
>
> "S1" "S2" "S3" "S4" "S5"
> 1 3 5 6 Na
> 3 Na 3 Na 2
>
> or better still:
>
> "S1" "S2" "S3" "S4" "S5"
> 1 3 5 6 0
> 3 0 3 0 2
>
>
> Any ihelp will be appreciated

You want to use the merge() function, which will enable you to perform a match of the common columns in the two vectors. Note that the result of merge() will create a data frame and the column order will be based upon the common columns first, so in this case S1 and S3:

# Set 'all = TRUE' to include all rows
DF <- merge(d1, d2, all = TRUE)   

> DF

  S1 S3 S2 S4 S5
1 1 5 3 6 NA
2 3 3 NA NA 2

We can then reorder the columns using names():

DF <- DF[, order(names(DF))]

> DF

  S1 S2 S3 S4 S5
1 1 3 5 6 NA
2 3 NA 3 NA 2

Note that NA has a specific intent in R relative to missing or undefined values. Setting NA's to 0 may have behavioral impacts that you need to be aware of depending upon what you intend to do:

# Set NA's in DF to 0
DF[is.na(DF)] <- 0

> DF

  S1 S2 S3 S4 S5
1 1 3 5 6 0
2 3 0 3 0 2

See ?merge, ?order and ?is.na for more information.

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 May 17 23:40:56 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 18 May 2006 - 00:10:17 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.