How can I merge and maintain the row order of one input?
dataframe, merge, r, sorting
Solution
You can do this with `match` and subsetting `key` by the result:
bottles <- key[match(samp, key$num),]
# rownames are odd because they must be unique, clean them up
rownames(bottles) <- seq(NROW(bottles))
Problem
I have a data frame that relates bottle numbers to their volumes (`key` in the example below). I want to write a function that will take any list of bottle numbers (`samp`) and return a list of the bottle volumes while maintaining the bottle number order in `samp`. The function below correctly matches the bottle numbers and volumes but sorts the output by ascending bottle number. How can I maintain the order of `samp` with `merge`? Setting `sort=FALSE` results in an "unspecified order". Example ``` samp <- c(9, 1, 4, 1) num <- 1:10 vol <- sample(50:100, 10) key <- data.frame(num, vol) matchFun <- function(samp, key) { out <- merge(as.data.frame(samp), key, by.x="samp", by.y="num") return(out$vol) } ```