Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge and maintain the row order of one input? [duplicate]

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)
  }
like image 641
DQdlM Avatar asked Jun 21 '12 18:06

DQdlM


2 Answers

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))
like image 91
Joshua Ulrich Avatar answered Sep 28 '22 12:09

Joshua Ulrich


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")
like image 39
guyabel Avatar answered Sep 28 '22 11:09

guyabel