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)
}
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))
join
in the plyr
package is great for this...
samp <- c(9, 1, 4, 1)
num <- 1:10
vol <- sample(50:100, 10)
key <- data.frame(num, vol)
samp<-as.data.frame(samp)
names(samp)<-"num"
library("plyr")
join(key,samp,type="right")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With