首页 文章

如何选择和删除特定元素或在向量或矩阵中找到它们的索引?

提问于
浏览
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

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

1 回答

  • 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中,只需用 ! 作为前缀,因为'%in%返回一个逻辑向量

    which(!y%in%x)
    
    ##[1] 3 5 8
    

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

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

相关问题