How to divide each column by a particular column in R?


To divide each column by a particular column, we can use division sign (/). For example, if we have a data frame called df that contains three columns say x, y, and z then we can divide all the columns by column z using the command df/df[,3].

Example

Consider the below data frame −

 Live Demo

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

Output

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

Dividing all columns of df1 by column x3 −

Example

df1/df1[,3]

Output

     x1         x2       x3
1  1.4000000  1.4000000  1
2  1.4000000  1.2000000  1
3  1.0000000  0.4285714  1
4  0.4000000  0.8000000  1
5  3.0000000  8.0000000  1
6  1.0000000  1.5000000  1
7  1.0000000  1.2500000  1
8  0.3750000  0.5000000  1
9  1.5000000  1.7500000  1
10 0.7142857  1.1428571  1
11 1.6666667  2.0000000  1
12 1.5000000  1.5000000  1
13 1.2000000  0.4000000  1
14 3.0000000  2.0000000  1
15 2.0000000  1.0000000  1
16 1.0000000  0.8571429  1
17 1.0000000  1.6000000  1
18 1.3333333  1.3333333  1
19 0.0000000  0.5000000  1
20 1.0000000  0.8333333  1

Example

 Live Demo

y1<-rpois(20,10)
y2<-rpois(20,10)
y3<-rpois(20,10)
df2<-data.frame(y1,y2,y3)
df2

Output

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

Dividing all columns of df2 by column y3 −

Example

df2/df2[,3]

Output

     y1         y2       y3
1  0.4444444  0.7777778  1
2  1.2222222  0.7777778  1
3  1.0909091  1.1818182  1
4  1.0666667  0.4000000  1
5  0.7272727  1.4545455  1
6  2.5000000  1.7500000  1
7  1.3333333  2.0000000  1
8  1.1818182  0.6363636  1
9  1.1000000  1.4000000  1
10 0.8888889  1.3333333  1
11 0.9285714  1.0714286  1
12 2.6000000  2.6000000  1
13 1.2222222  0.7777778  1
14 2.0000000  2.4000000  1
15 0.6923077  0.7692308  1
16 0.7500000  0.8333333  1
17 1.1428571  1.1428571  1
18 1.2222222  1.0000000  1
19 0.8181818  0.7272727  1
20 0.6666667  1.0833333  1

Updated on: 16-Mar-2021

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements