How to divide the row values by row sum in R data frame?

R ProgrammingServer Side ProgrammingProgramming

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

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rpois(25,1)
y<-rpois(25,2)
z<-rpois(25,2)
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 1 1 1
2 2 1 2
3 4 4 1
4 0 1 0
5 2 4 1
6 2 4 3
7 0 1 1
8 0 1 1
9 3 3 2
10 2 4 3
11 1 1 1
12 0 3 2
13 2 2 1
14 1 2 6
15 0 1 0
16 1 2 3
17 1 3 2
18 0 4 2
19 2 2 1
20 1 1 3
21 0 2 2
22 1 5 3
23 1 3 3
24 0 2 2
25 2 0 5

Divide the data frame row values by row sum

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

 Live Demo

x<-rpois(25,1)
y<-rpois(25,2)
z<-rpois(25,2)
df<-data.frame(x,y,z)
df_new<-t(apply(df,1, function(x) x/sum(x)))
df_new

Output

         x          y       z
[1,] 0.3333333 0.3333333 0.3333333
[2,] 0.4000000 0.2000000 0.4000000
[3,] 0.4444444 0.4444444 0.1111111
[4,] 0.0000000 1.0000000 0.0000000
[5,] 0.2857143 0.5714286 0.1428571
[6,] 0.2222222 0.4444444 0.3333333
[7,] 0.0000000 0.5000000 0.5000000
[8,] 0.0000000 0.5000000 0.5000000
[9,] 0.3750000 0.3750000 0.2500000
[10,] 0.2222222 0.4444444 0.3333333
[11,] 0.3333333 0.3333333 0.3333333
[12,] 0.0000000 0.6000000 0.4000000
[13,] 0.4000000 0.4000000 0.2000000
[14,] 0.1111111 0.2222222 0.6666667
[15,] 0.0000000 1.0000000 0.0000000
[16,] 0.1666667 0.3333333 0.5000000
[17,] 0.1666667 0.5000000 0.3333333
[18,] 0.0000000 0.6666667 0.3333333
[19,] 0.4000000 0.4000000 0.2000000
[20,] 0.2000000 0.2000000 0.6000000
[21,] 0.0000000 0.5000000 0.5000000
[22,] 0.1111111 0.5555556 0.3333333
[23,] 0.1428571 0.4285714 0.4285714
[24,] 0.0000000 0.5000000 0.5000000
[25,] 0.2857143 0.0000000 0.7142857
raja
Published on 06-Aug-2021 11:45:35
Advertisements