R从另一个向量中选择矩阵中的行(匹配,%in) [英] R select rows in matrix from another vector (match, %in)

查看:78
本文介绍了R从另一个向量中选择矩阵中的行(匹配,%in)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含6列和100000行的数据框.我想基于另一个向量 reducedScenIds (10,000行)中的索引/数字选择矩阵 originScen 中的行.我通过检查Y的每个成员的值是否与数据框X的列1中的值匹配来选择行.现在,第一列可以对Y的每个值进行多个匹配.

Say I have a dataframe with 6 columns and 100000 rows. I want to select rows in matrix originScen based on the indices/numbers in another vector reducedScenIds (10,000 rows). I select the rows by checking if the value of each member of Y matches the value in column 1 of the dataframe X. Now the first column can have multiple matches for each value of Y.

所以我用了下面的

reducedSet <- originScen[which(originScen[,1] %in% reducedScenarioIds),]

我对结果感到满意,只是哪个%in%似乎破坏了 reducedScenarioIds 向量的顺序.最终的 reducedSet 具有根据在 reducedScenarioIds 向量中找到的id的升序选择的行,而不是完全相同的顺序.

I am ok with the results except that which and %in% seems to destroy the order of reducedScenarioIds vector. The final reducedSet has rows selected based on ascending order of ids found in the reducedScenarioIds vector and not the exact same order.

originScen[,1] 可以为 reducedScenarioIds

有人有替代解决方案吗?

Anyone have an alternate solution?

谢谢

推荐答案

尝试一下:

reducedSet <- originScen[originScen[,1] %in% reducedScenarioIds,][order(na.exclude(match(originScen[,1], reducedScenarioIds))),]

这篇关于R从另一个向量中选择矩阵中的行(匹配,%in)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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