How to remove repeated elements in a vector, simil

2019-03-09 15:38发布

I have a vector with repeated elements, and would like to remove them so that each element appears only once.

In Python I could construct a Set from a vector to achieve this, but how can I do this in R?

3条回答
来,给爷笑一个
2楼-- · 2019-03-09 16:22

You can check out unique function.

 > v = c(1, 1, 5, 5, 2, 2, 6, 6, 1, 3)
 > unique(v)
 [1] 1 5 2 6 3
查看更多
做个烂人
3楼-- · 2019-03-09 16:29

This does the same thing. Slower, but useful if you also want a logical vector of the duplicates:

v[duplicated(v)]
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-09 16:36

To remove contiguous duplicated elements only, you can compare the vector with a shifted version of itself:

v <- c(1, 1, 5, 5, 5, 5, 2, 2, 6, 6, 1, 3, 3)
v[c(TRUE, !v[-length(v)] == v[-1])]
[1] 1 5 2 6 1 3

The same can be written a little more elegantly using dplyr:

library(dplyr)
v[v != lag(v)]
[1] NA  5  2  6  1  3

The NA returned by lag() removes the first value, to keep the first value, you can change the default to a value that will be different from the first value.

v[v != lag(v, default = !v[1])]
[1] 1 5 2 6 1 3
查看更多
登录 后发表回答