R-使用匹配运算符时保留顺序(%in%) [英] R - preserve order when using matching operators (%in%)

查看:120
本文介绍了R-使用匹配运算符时保留顺序(%in%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用匹配运算符来从单独的数据帧中获取出现在矩阵中的值.但是,结果矩阵具有的值的顺序是它们在数据帧中出现的顺序,而不是在原始矩阵中出现的顺序.有什么方法可以使用匹配运算符保留原始矩阵的顺序吗?

I am using matching operators to grab values that appear in a matrix from a separate data frame. However, the resulting matrix has the values in the order they appear in the data frame, not in the original matrix. Is there any way to preserve the order of the original matrix using the matching operator?

这是一个简单的例子:

vec=c("b","a","c"); vec

df=data.frame(row.names=letters[1:5],values=1:5); df

df[rownames(df) %in% vec,1]

这将产生> [1] 1 2 3,这是"a" "b" "c"在数据框中出现的顺序.但是,我想生成>[1] 2 1 3,这是它们在原始向量中出现的顺序.

This produces > [1] 1 2 3 which is the order "a" "b" "c" appears in the data frame. However, I would like to generate >[1] 2 1 3 which is the order they appear in the original vector.

谢谢!

推荐答案

使用match.

df[match(vec, rownames(df)), ]
# [1] 2 1 3

请注意,如果vecrownames(df)中的值重复,则match可能不会达到预期的效果.

Be aware that if you have duplicate values in either vec or rownames(df), match may not behave as expected.

修改: 我刚刚意识到,行名索引将更简单,更优雅地解决您的问题:

I just realized that row name indexing will solve your issue a bit more simply and elegantly:

df[vec, ]
# [1] 2 1 3

这篇关于R-使用匹配运算符时保留顺序(%in%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆