R select rows in matrix from another vector (match

2019-08-12 16:25发布

问题:

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.

So I used the below

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

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.

The originScen[,1] can have duplicate entries for each entry in reducedScenarioIds

Anyone have an alternate solution?

Thanks

回答1:

Try this:

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


标签: r select match