How to create a column with ratio of two columns in R?


To create a new column with ratio of two columns in an R data frame, we can use division sign.

For example, if we have a data frame called df that contains two columns say X and Y and we want to create a new column with ratio of X and Y then we can use the below given command −

df$Ratio_X_Y<-df$X/df$Y

Example 1

Following snippet creates a sample data frame −

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

The following dataframe is created −

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

To find ratio of x1 and x2, add the following code to the above snippet −

x1<-rpois(20,2)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1$Ratio_x1_x2<-df1$x1/df1$x2
df1

Output

If you execute all the above given snippets as a single program, it generates the following output −

   x1 x2 Ratio_x1_x2
1  0  3  0.0000000
2  5  1  5.0000000
3  2  3  0.6666667
4  2  1  2.0000000
5  1  3  0.3333333
6  2  4  0.5000000
7  1  0        Inf
8  1  0        Inf
9  3  3  1.0000000
10 1  2  0.5000000
11 3  3  1.0000000
12 0  5  0.0000000
13 3  0        Inf
14 2  2  1.0000000
15 3  3  1.0000000
16 2  0        Inf
17 2  6  0.3333333
18 2  1  2.0000000
19 0  0        NaN
20 1  3  0.3333333

Example 2

Following snippet creates a sample data frame −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
df2<-data.frame(y1,y2)
df2

The following dataframe is created −

    y1    y2
1  -0.6  0.0
2  -1.3  0.9
3  -0.6 -0.3
4   1.8 -1.0
5   1.1  0.4
6  -0.3  0.2
7  -0.8 -1.5
8   1.2 -1.2
9   0.2  1.2
10  0.1 -0.4
11 -2.1 -1.9
12  1.5  0.5
13 -0.8 -0.5
14  0.4  0.8
15  0.9  0.9
16  1.2 -0.3
17  1.3 -1.3
18 -0.2  2.5
19  0.6  0.8
20 -2.1  0.7

To find ratio of y1 and y2, add the following code to the above snippet −

y1<-round(rnorm(20),1)
y2<-round(rnorm(20),1)
df2<-data.frame(y1,y2)
df2$Ratio_y1_y2<-df2$y1/df2$y2
df2

Output

If you execute all the above given snippets as a single program, it generates the following output −

     y1  y2    Ratio_y1_y2
1  -0.6  0.0         Inf
2  -1.3  0.9  -1.4444444
3  -0.6 -0.3   2.0000000
4   1.8 -1.0  -1.8000000
5   1.1  0.4   2.7500000
6  -0.3  0.2  -1.5000000
7  -0.8 -1.5   0.5333333
8   1.2 -1.2  -1.0000000
9   0.2  1.2   0.1666667
10  0.1 -0.4  -0.2500000
11 -2.1 -1.9   1.1052632
12  1.5  0.5   3.0000000
13 -0.8 -0.5   1.6000000
14  0.4  0.8   0.5000000
15  0.9  0.9   1.0000000
16  1.2 -0.3  -4.0000000
17  1.3 -1.3  -1.0000000
18 -0.2  2.5  -0.0800000
19  0.6  0.8   0.7500000
20 -2.1  0.7  -3.0000000

Updated on: 23-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements