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

R ProgrammingServer Side ProgrammingProgramming

To divide the row values by row mean in R data frame, 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 mean.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-sample(1:50,25)
> y<-sample(1:50,25)
> 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 42 23
2 2 37
3 6 42
4 34 28
5 50 19
6 41 46
7 35 38
8 33 7
9 32 9
10 47 10
11 3 4
12 25 39
13 11 22
14 31 31
15 45 41
16 10 36
17 8 34
18 26 1
19 44 20
20 21 17
21 19 26
22 4 14
23 30 35
24 20 47
25 29 40

Divide the data frame row values by row mean

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

 Live Demo

> x<-sample(1:50,25)
> y<-sample(1:50,25)
> df<-data.frame(x,y)
> df_new<-t(apply(df,1, function(x) x/mean(x)))
> df_new

Output

x y
[1,] 1.2923077 0.70769231
[2,] 0.1025641 1.89743590
[3,] 0.2500000 1.75000000
[4,] 1.0967742 0.90322581
[5,] 1.4492754 0.55072464
[6,] 0.9425287 1.05747126
[7,] 0.9589041 1.04109589
[8,] 1.6500000 0.35000000
[9,] 1.5609756 0.43902439
[10,] 1.6491228 0.35087719
[11,] 0.8571429 1.14285714
[12,] 0.7812500 1.21875000
[13,] 0.6666667 1.33333333
[14,] 1.0000000 1.00000000
[15,] 1.0465116 0.95348837
[16,] 0.4347826 1.56521739
[17,] 0.3809524 1.61904762
[18,] 1.9259259 0.07407407
[19,] 1.3750000 0.62500000
[20,] 1.1052632 0.89473684
[21,] 0.8444444 1.15555556
[22,] 0.4444444 1.55555556
[23,] 0.9230769 1.07692308
[24,] 0.5970149 1.40298507
[25,] 0.8405797 1.15942029
raja
Published on 03-Aug-2021 11:26:21
Advertisements