0

假设我有两个向量:

x <- c(1,16,20,7,2)

y <- c(1, 7, 5,2,4,16,20,10)

我想删除y不在x. 也就是说,我想5, 4, 10y.

y
[1] 1 7 2 16 20 

最后,我想要向量x并且y必须拥有相同的元素。顺序无所谓。

我的想法:该match函数列出了两个向量包含匹配元素的索引,但我需要一个基本上相反的函数。我需要一个函数来显示两个向量中的元素不匹配的索引。

# this lists the indices in y that match the elements in x
match(x,y)
[1] 1 6 7 2 4   # these are the indices that I want; I want to remove
                # the other indices from y

有谁知道如何做到这一点?谢谢你

4

1 回答 1

2

你在追求intersect

intersect(x,y)
## [1]  1 16 20  7  2

如果您想要yin x、 usingwhich%in%(在内部%in%使用的元素的索引match,那么您在这里是正确的)

which(y %in% x)
## [1] 1 2 4 6 7

正如@joran 在评论中指出的那样,intersect将删除重复项,因此如果您想返回真正的匹配项,这可能是一个安全的选择,例如

intersection <- function(x,y){.which <- intersect(x,y)
 .in <- x[which(x %in% y)]
 .in}


x <- c(1,1,2,3,4)
y <- c(1,2,3,3)

intersection(x,y)
## [1] 1 1 2 3
# compare with
intersect(x,y)
## [1] 1 2 3

intersection(y,x)
## [1] 1 2 3 3
# compare with 
intersect(y, x)
## [1] 1 2 3

然后,您需要小心使用此修改后的功能进行排序(intersect因为它会删除重复的元素,所以可以避免这种情况)


如果你想要 y 的那些元素的索引不在 x 中,只需加上前缀,!因为 `%in% 返回一个逻辑向量

which(!y%in%x)

##[1] 3 5 8

或者,如果您希望元素使用setdiff

setdiff(y,x)
## [1]  5  4 10
于 2012-11-08T04:27:37.770 回答