How to minus one column from another in an R matrix?


To minus one column from another in an R matrix, we first need to read the matrix as a data frame using as.data.frame then find minus the columns using minus sign and accessing the column of the data frame. To understand how it can be done look at the steps in below examples.

Example

Consider the below data frame −

 Live Demo

M1<-matrix(rpois(40,8),ncol=2)
M1

Output

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

Example

Reading the matrix M1 as data frame −

M1<-as.data.frame(M1)
M1

Output

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

Example

Finding the difference in columns V1 and V2 of M1 −

M1$Difference<-(M1$V1-M1$V2)
M1

Output

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

Example

 Live Demo

M2<-matrix(rpois(40,5),ncol=2)
M2

Output

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

Example

Finding the difference in columns V1 and V2 of M2 −

M2<-as.data.frame(M2)
M2

Output

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

Example

Finding the difference in columns V1 and V2 of M2 −

M2$Difference<-(M2$V1-M2$V2)
M2

Output

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

Updated on: 16-Mar-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements