【问题标题】:How to select and remove specific elements or find their index in a vector or matrix?如何选择和删除特定元素或在向量或矩阵中找到它们的索引?
【发布时间】:2012-10-28 06:09:16
【问题描述】:

假设我有两个向量:

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

有人知道怎么做吗?谢谢

【问题讨论】:

    标签: r vector matrix indices


    【解决方案1】:

    你关注intersect

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

    如果您想要 x 中的 y 元素的索引,请使用 which%in%%in% 在内部使用 match,所以您在这里是在正确的轨道上)

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

    正如@joran 在 cmets 中指出的那样,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
    

    【讨论】:

    • 我能想到的唯一曲线球是intersect 会丢弃重复的元素。
    • 谢谢,我认为这是我需要的功能,但是如何列出 y 中不包含 x 中的元素的索引?
    • @joran,好点,我添加了一个返回所有元素的函数,还有 setdiff 的例子而不是 in
    • 谢谢@mnel 和joran。如果我有更多的声望点,我会给你们两个竖起大拇指。
    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多