如何合并和维护一个输入的行顺序? [英] How can I merge and maintain the row order of one input?
本文介绍了如何合并和维护一个输入的行顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,将瓶子编号与其卷( key
)在下面的示例中相关联。我想编写一个函数,它将使用任何瓶子编号列表( samp
),并返回瓶子列表,同时保持瓶子编号顺序 samp
。
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.
可以使用 merge
保持 samp
的顺序吗?
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)
}
推荐答案
您可以使用匹配
并将结果键入键
bottles <- key[match(samp, key$num),]
# rownames are odd because they must be unique, clean them up
rownames(bottles) <- seq(NROW(bottles))
这篇关于如何合并和维护一个输入的行顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文