R:删除矢量中的重复元素 [英] R: Removing duplicate elements in a vector

查看:159
本文介绍了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

我想摆脱重复,并得到这样的东西:

 > [1] 1 2 3 7 

我的尝试

  y = x [duplicated(x)] 

> y
[1] 4 5 6

> x [x!= y]
[1] 1 2 3 7
警告信息:
在x!= y中:较长的对象长度不是较短对象长度的倍数
>

我做错了什么?这个错误是我应该担心的吗?

有没有另外一种方法可以做到这一点,而不会出现错误?

解决方案

测试!

  x < -  c(1,2,3,4,5,6,4,5,6,7) 
x1 <-c(-1,-1,2,8,8,15)

keep_singles < - 函数(v){
v [!(v% in%v [duplicateated(v)])]
}

keep_singles(x)

[1] 1 2 3 7

keep_singles(x1)

[1] 2 15


I have a vector like this:

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 

My attempt

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屋!

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