[R] Combining Vectors
Marc Schwartz
MSchwartz at mn.rr.com
Wed May 17 15:32:34 CEST 2006
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
More information about the R-help
mailing list