Syntax error How to divide data frame row values by row variance in R?

How to divide data frame row values by row variance in R?



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

Create the data frame

Let's create a data frame as shown below −

 Live Demo

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

Divide the data frame row values by row variance

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

 Live Demo

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

Output

         x      y      z
[1,]    Inf    Inf    Inf
[2,] 0.750000 0.0 0.0000000
[3,] 0.000000 1.0 0.0000000
[4,] 2.000000 1.0 0.0000000
[5,] 3.000000 0.0 0.0000000
[6,]    Inf    Inf    Inf
[7,] 1.000000 3.0 2.0000000
[8,] 3.000000 3.0 6.0000000
[9,] 0.000000 3.0 3.0000000
[10,]    Inf   Inf    Inf
[11,] 1.000000 0.0 1.0000000
[12,] 1.285714 0.0 0.4285714
[13,] 1.000000 0.5 0.0000000
[14,] 3.000000 0.0 0.0000000
[15,] 6.000000 3.0 3.0000000
[16,] 1.500000 0.0 0.0000000
[17,] 3.000000 2.0 1.0000000
[18,]    NaN    NaN    NaN
[19,] 1.000000 0.0 2.0000000
[20,] 0.000000 1.0 2.0000000
[21,] 3.000000 0.0 3.0000000
[22,] 0.000000 1.0 2.0000000
[23,] 3.000000 0.0 0.0000000
[24,] 0.000000 1.5 1.5000000
[25,] 6.000000 3.0 3.0000000
Updated on: 2021-08-14T08:35:19+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements