Learn R Programming

Kmisc (version 0.2.0)

kMerge: Merge (Left Join) with Index Retainment

Description

merge will mangle the order of the data frames it is merging. This is a simple modification to ensure that the order in data frame x is preserved when doing a 'left join'; ie, merge( x, y, all.x=TRUE, ... ). That is, if we want to merge a data frame x with another data frame y, we can merge in the parts of y whose index matches with that of x, while preserving the ordering of x.

Usage

kMerge(x, y, by, ...)

Arguments

x
the data.frame you wish to merge y into
y
the data.frame to be merged
by
the variable to merge over
...
optional arguments passed to merge

Value

  • data.frame

Details

The function requires you to specify the by argument; ie, you must have a shared column in your data frames x and y.

See Also

merge

Examples

Run this code
x <- data.frame( id=5:1, nums=rnorm(5) )
y <- data.frame( id=1:3, labels=c(1, 2, 2) )
merge(x, y, all.x=TRUE) ## re-ordered the data.frame
merge(x, y, all.x=TRUE, sort=FALSE) ## nope - NAs cause problems
kMerge(x, y, by="id") ## preserves ordering of x, even with NAs

## an id entry appears more than once in y
y <- data.frame( id=c(1, 1, 2), labels=c(1, 2, 3) )
kMerge(x, y, by="id")

Run the code above in your browser using DataLab