2012-11-08 21 views
0

比方說,我有兩個向量:如何選擇和刪除特定元素或在矢量或矩陣中找到它們的索引?

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

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

我想刪除元素y不在x。也就是說,我想從y中刪除元素5, 4, 10

y 
[1] 1 7 2 16 20 

最後,我想矢量和xy不得不相同的元件。順序無關緊要。

我的想法: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 

有沒有人知道如何做到這一點?謝謝

回答

2

您是後intersect

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

如果你想在xy元素的索引,使用which%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中,只需用!前綴`%在%返回一個邏輯向量

which(!y%in%x) 

##[1] 3 5 8 

或者,如果你想要的元素中使用setdiff

setdiff(y,x) 
## [1] 5 4 10 
+1

只有弧線球我能想到的是,'intersect'將下降重複的元素。 – joran

+0

謝謝我認爲這是我需要的功能,但是如何列出'y'中不包含'x'中元素的索引? – user1313954

+0

@joran,好點,我添加了一個函數,將返回所有元素,也是setdiff的例子,而不是在 – mnel

相關問題