How to divide data frame rows in R by row minimum?


To divide the data frame row values by row minimum in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use apply function to divide the data frame row values by row minimum.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-round(rnorm(25,25,8),0)
y<-round(rnorm(25,25,8),0)
df<-data.frame(x,y)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x y
1  37 25
2  23 24
3  10 20
4  27 22
5  32 43
6   7 25
7  29 33
8   7 29
9  17 19
10 15 19
11 37 24
12 22 14
13 29 23
14 17 12
15 26 17
16 37 11
17 21 22
18 20 38
19 20 20
20 28 29
21 18 24
22 31 23
23 43 14
24 24 30
25 16 19

Divide the data frame row values by row minimum

Using apply function to divide the row values of df by row minimum −

 Live Demo

x<-round(rnorm(25,25,8),0)
y<-round(rnorm(25,25,8),0)
df<-data.frame(x,y)
df_new<-t(apply(df,1, function(x) x/min(x)))
df_new

Output

         x       y
[1,] 1.480000 1.000000
[2,] 1.000000 1.043478
[3,] 1.000000 2.000000
[4,] 1.227273 1.000000
[5,] 1.000000 1.343750
[6,] 1.000000 3.571429
[7,] 1.000000 1.137931
[8,] 1.000000 4.142857
[9,] 1.000000 1.117647
[10,] 1.000000 1.266667
[11,] 1.541667 1.000000
[12,] 1.571429 1.000000
[13,] 1.260870 1.000000
[14,] 1.416667 1.000000
[15,] 1.529412 1.000000
[16,] 3.363636 1.000000
[17,] 1.000000 1.047619
[18,] 1.000000 1.900000
[19,] 1.000000 1.000000
[20,] 1.000000 1.035714
[21,] 1.000000 1.333333
[22,] 1.347826 1.000000
[23,] 3.071429 1.000000
[24,] 1.000000 1.250000
[25,] 1.000000 1.187500

Updated on: 13-Aug-2021

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements