How to divide row values of a numerical column based on categorical column values in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

If we have a categorical column that has two or more categories and a numerical column then we might want to divide the one category numerical value from other category numerical value. This can be done by using divide sign / but we need to use the proper subset of the values.

Example

Consider the below data frame −

 Live Demo

x1<-rep(LETTERS[1:2],10)
y1<-rpois(20,5)
df1<-data.frame(x1,y1)
df1

Output

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

Dividing y1 of B by A in df1 −

Example

df1$y1[which(df1$x1=="B")]/df1$y1[which(df1$x1=="A")]

Output

[1] 1.1250000 1.2000000 0.6666667 0.3750000 1.5000000 1.8333333 1.5000000 [8] 1.2500000 1.4000000 0.1000000

Example

 Live Demo

x2<-rep(c("India","USA","China","Turkey"),5)
y2<-sample(1:9,20,replace=TRUE)
df2<-data.frame(x2,y2)
df2

Output

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

Dividing y2 of India by USA in df2 −

Example

df2$y2[which(df2$x2=="India")]/df2$y2[which(df2$x2=="USA")]

Output

[1] 1.8000000 0.1111111 8.0000000 0.3333333 7.0000000

Dividing y2 of India by Turkey in df2 −

Example

df2$y2[which(df2$x2=="India")]/df2$y2[which(df2$x2=="Turkey")]

Output

[1] 4.5000000 1.0000000 0.8888889 0.5000000 1.7500000

Dividing y2 of Turkey by China in df2 −

Example

df2$y2[which(df2$x2=="Turkey")]/df2$y2[which(df2$x2=="China")]

Output

[1] 0.2857143 0.1428571 1.2857143 0.2500000 0.8000000
raja
Published on 07-Dec-2020 05:38:02
Advertisements