How to subtract one data frame from another in R?


If we have two data frames with same number of columns of same data type and equal number of rows then we might want to find the difference between the corresponding values of the data frames. To do this, we simply need to use minus sign. For example, if we have data-frames df1 and df2 then the subtraction can be found as df1-df2.

Consider the below data frame −

Example

 Live Demo

x1<-rpois(20,5)
x2<-rpois(20,8)
df1<-data.frame(x1,x2)
df1

output

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

Example

 Live Demo

y1<-sample(0:10,20,replace=TRUE)
y2<-sample(0:10,20,replace=TRUE)
df2<-data.frame(y1,y2)
df2

output

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

Subtracting df2 from df1 −

Example

df1-df2

output

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

Let’s have a look at another example −

Subtracting df2 from df1 −

Example

 Live Demo

V1<-rpois(20,1)
V2<-rpois(20,10)
V3<-rpois(20,12)
df_V<-data.frame(V1,V2,V3)
df_V

output

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

Example

 Live Demo

W1<-sample(0:5,20,replace=TRUE)
W2<-sample(0:10,20,replace=TRUE)
W3<-sample(0:15,20,replace=TRUE)
df_W<-data.frame(W1,W2,W3)
df_W

output

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

Subtracting df_W from df_V −

Example

df_V-df_W

output

V1 V2 V3
1 -5 5 12
2 -3 12 7
3 0 10 7
4 -1 9 14
5 -2 6 17
6 2 -2 4
7 0 7 5
8 0 2 -1
9 -1 6 -4
10 -2 5 -4
11 -3 0 7
12 -2 11 -4
13 -3 2 -1
14 0 3 - 3
15 -1 7 2
16 2 2 9
17 -3 6 2
18 -2 -2 -1
19 2 6 14
20 -3 10 4

Updated on: 14-Oct-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements