R:删除向量中的重复元素 [英] R: Removing duplicate elements in a vector
本文介绍了R:删除向量中的重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的向量:
x = c(1,2,3,4,5,6,4,5,6,7)
> x
[1] 1 2 3 4 5 6 4 5 6 7
我想摆脱重复并得到这样的东西:
I want to get rid of duplicates and get something like this:
> [1] 1 2 3 7
我的尝试
y = x[duplicated(x)]
> y
[1] 4 5 6
> x[x!=y]
[1] 1 2 3 7
Warning message:
In x != y : longer object length is not a multiple of shorter object length
>
我做错了什么?
这个错误是我应该担心的吗?
有没有其他方法可以做到这一点而不会出错?
What am I doing wrong?
Is this error something I should worry about?
Is there another way to do this without getting an error?
推荐答案
注意在测试中使用连续数字!
Beware using consecutive numbers in your tests!
x <- c(1,2,3,4,5,6,4,5,6,7)
x1 <- c(-1, -1, 2, 8, 8, 15)
keep_singles <- function(v){
v[!(v %in% v[duplicated(v)])]
}
keep_singles(x)
[1] 1 2 3 7
keep_singles(x1)
[1] 2 15
这篇关于R:删除向量中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文