如何在R中选择数据框中不存在于另一个数据框中的行?


有时我们需要查找两个数据框之间不相同的行,而不是查找公共行。当我们预期不相同的行数很多而不是很少时,这通常很有用。我们可以使用否定运算符(用感叹号表示)和子集函数来做到这一点。

示例

考虑以下数据框:

 在线演示

> x1<-sample(1:10,20,replace=TRUE)
> y1<-sample(1:10,20,replace=TRUE)
> df1<-data.frame(x1,y1)
> df1

输出

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

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

示例

 在线演示

> x2<-sample(1:10,20,replace=TRUE)
> y2<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(x2,y2)
> df2

输出

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

现在假设我们想要获取df2变量y2的一个子集,这些子集不存在于df1的y1中,那么可以按如下方式进行:

> subset(df2,!(y2%in%df1$y1))
x2 y2
16 1 7
<0 rows> (or 0-length row.names)

类似地,获取df2变量y2的一个子集,这些子集不存在于df1的x1中,那么可以按如下方式进行:

> subset(df2,!(y2%in%df1$x1))
[1] x2 y2
<0 rows> (or 0-length row.names)

让我们再看一个例子:

示例

 在线演示

> x1<-rep(1:10,2)
> df1<-data.frame(x1)
> df1

输出

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

 在线演示

> x2<-rep(1:5,4)
> df2<-data.frame(x2)
> df2

输出

 x2
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5
11 1
12 2
13 3
14 4
15 5
16 1
17 2
18 3
19 4
20 5
> subset(df1,!(x1%in%df2$x2))

输出

 x1
6 6
7 7
8 8
9 9
10 10
16 6
17 7
18 8
19 9
20 10

更新于:2020年9月4日

2K+浏览量

启动你的职业生涯

通过完成课程获得认证

开始学习
广告