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

R ProgrammingServer Side ProgrammingProgramming

To divide the data frame row values by row maximum 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 maximum.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rpois(20,5)
y<-rpois(20,4)
z<-rpois(20,10)
df<-data.frame(x,y,z)
df

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

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

Divide the data frame row values by row maximum

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

 Live Demo

x<-rpois(20,5)
y<-rpois(20,4)
z<-rpois(20,10)
df<-data.frame(x,y,z)
df_new<-t(apply(df,1, function(x) x/max(x)))
df_new

Output

        x          y         z
[1,] 0.1538462 0.15384615 1.0000000
[2,] 0.1428571 0.07142857 1.0000000
[3,] 0.4117647 0.17647059 1.0000000
[4,] 0.2727273 0.27272727 1.0000000
[5,] 0.6000000 1.00000000 0.9000000
[6,] 1.0000000 0.83333333 1.0000000
[7,] 0.4000000 0.40000000 1.0000000
[8,] 0.4285714 0.85714286 1.0000000
[9,] 1.0000000 0.42857143 0.8571429
[10,] 0.3571429 0.28571429 1.0000000
[11,] 1.0000000 0.50000000 0.9000000
[12,] 0.7000000 0.60000000 1.0000000
[13,] 0.3000000 0.60000000 1.0000000
[14,] 0.7000000 0.10000000 1.0000000
[15,] 1.0000000 0.40000000 1.0000000
[16,] 0.6666667 1.00000000 0.8888889
[17,] 0.2000000 0.40000000 1.0000000
[18,] 0.1875000 0.25000000 1.0000000
[19,] 0.4444444 1.00000000 0.7777778
[20,] 0.1818182 0.81818182 1.0000000
raja
Published on 09-Aug-2021 08:56:03
Advertisements