这个问题在这里已经有了答案:
Finding ALL duplicate rows, including "elements with smaller subscripts"
(8 个回答)
4年前关闭。
我有一个这样的向量:
x = c(1,2,3,4,5,6,4,5,6,7)
> x
[1] 1 2 3 4 5 6 4 5 6 7
我想摆脱重复并得到这样的东西:
> [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
>
我究竟做错了什么?这个错误是我应该担心的吗?
有没有其他方法可以做到这一点而不会出错?
最佳答案
小心在测试中使用连续数字!
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:删除向量中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381174/