How to remove repeated elements in a vector, similar to 'set' in Python

蓝咒 提交于 2019-12-02 17:53:18
sus_mlm

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

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

v[duplicated(v)]

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!