Learn R Programming

Kmisc (version 0.5.0)

kMerge: Merge (Left Join) with Order 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 = intersect(names(x), names(y)), by.x = by, by.y = by, ...)

Arguments

x
the data.frame you wish to merge y into.
y
the data.frame to be merged.
by
specifications of the columns used for merging. See 'Details' of merge.
by.x
specifications of the columns used for merging. See 'Details' of merge.
by.y
specifications of the columns used for merging. See 'Details' of merge.
...
optional arguments passed to merge.

Value

data.frame

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