如何在 R 中检查数据框列是否包含重复值?


为了检查数据框列是否包含重复的值,我们可以使用 duplicated 函数和 any 联合使用。例如,如果我们有一个名为 df 的数据框,它包含一个列 ID,接着我们可以使用命令检查 ID 是否包含重复值 −

any(duplicated(df$ID))

示例 1

考虑下面的数据框 −

 实时演示

ID<-1:20
x<-rpois(20,1)
df1<-data.frame(ID,x)
df1

输出

    ID x
1   1  4
2   2  1
3   3  2
4   4  2
5   5  1
6   6  0
7   7  1
8   8  1
9   9  0
10 10  1
11 11  1
12 12  2
13 13  1
14 14  3
15 15  1
16 16  0
17 17  0
18 18  3
19 19  2
20 20  2

检查 x 是否包含任何重复数据 −

any(duplicated(df1$x))

[1] TRUE

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

 实时演示

S.No<-1:20
y<-round(rnorm(20,5,3),1)
df2<-data.frame(S.No,y)
df2

输出

   S.No  y
1   1   5.1
2   2   5.8
3   3   4.4
4   4  10.1
5   5   3.3
6   6   6.1
7   7   4.8
8   8  12.6
9   9   6.4
10 10   8.7
11 11   1.5
12 12   2.5
13 13   2.1
14 14   8.7
15 15   5.5
16 16   2.0
17 17   2.1
18 18   5.5
19 19   5.4
20 20   3.4

检查 y 是否包含任何重复数据 −

any(duplicated(df2$y))

[1] TRUE

更新于: 16-Mar-2021

2 千 + 浏览量

开启你的 事业

通过完成课程获得认证

开始
广告