merge is a very nice feature: it combines matrices and data.frames and returns data.frame.
Having fairly large character matrices, is there another good way to merge - without converting data.frame?
Comment 1: A small function for merging a named vector with a matrix or data.frame. Elements of a vector can refer to several entries in a matrix:
expand <- function(v,m,by.m,v.name='v',...) {
df <- do.call(rbind,lapply(names(v),function(x) {
pos <- which(m[,by.m] %in% v[x])
cbind(x,m[pos,],...)
}))
colnames(df)[1] <- v.name
df
}
Example:
v <- rep(letters,each=3)[seq_along(letters)]
names(v) <- letters
m <- data.frame(a=unique(v),b=seq_along(unique(v)),stringsAsFactors=F)
expand(v,m,'a')
source
share