删除序列中的重复数字 [英] Remove repeated numbers in a sequence

查看:106
本文介绍了删除序列中的重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为

c(3,3,...,9,9,...,2,2,...,3,3,...,7,7,...)

我想删除一个序列中的重复数字,而不破坏顺序。这就是我想获得的东西

I want to remove the repeated numbers in a sequence, without breaking the order. This is, I would like to obtain something like

c(3,9,2,3,7,...)

如何在R中做到这一点?

How can I do this in R?

推荐答案

我们可以尝试使用 rleid 重复。我们使用 rleid (来自 data.table )创建运行长度ID,以便仅相邻元素相等组成一组,得到不重复个值的逻辑索引,并将向量子集化。

We can try with rleid and duplicated. We create the run-length-ids with rleid (from data.table) so that only adjacent elements that are equal forms one group, get the logical index of not duplicated values and subset the vector.

library(data.table)
v1[!duplicated(rleid(v1))]
#[1] 3 9 2 3 7






或者如操作说明所述,我们可以使用 rle 基础R 中提取

rle(v1)$values
#[1] 3 9 2 3 7



数据



data

 v1 <- c(3,3,9,9,2,2,3,3,7,7)

这篇关于删除序列中的重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆