3

In R,

I have a vector of 5 unique elements:

X<-c("A","B","C","D","E") 

And a vector of repeated elements:

Y<- c("A","C","M","Z","B","C","C","R","V","D","D","B","A","V","E","E")

I want to obtain the position of elements of Y that a are in X becase Y are rownames of a matrix.

But Y[match(Y,X)] gives:

[1] "A" "M" NA  NA  "C" "M" "M" NA  NA  "Z" "Z" "C" "A" NA  "B" "B"

The response should be: c("A","C",NA,NA,"B","C","C",NA,NA,"D","D","B","A",NA,"E","E").

to select the rows:

Y[-which(is.na(Y[match(Y,X)]))]

Is there a better and more elegant alternative?

4

1 回答 1

3

您可以使用%in%

Y[Y %in% X]
[1] "A" "C" "B" "C" "C" "D" "D" "B" "A" "E" "E"

这有帮助吗?

于 2013-10-28T15:44:22.800 回答