How to subtract column values from column means in R data frame?


To subtract column values from column means in R data frame, we can follow the below steps −

  • First of all, create a data frame.
  • Then, find the column means using colMeans function.
  • After that, subtract column values from column means.

Creating the data frame

Let's create a data frame as shown below −

 Live Demo

> x1<-sample(1:100,20)
> x2<-sample(1:100,20)
> x3<-sample(1:100,20)
> df<-data.frame(x1,x2,x3)
> df

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

   x1  x2  x3
1  54  73  57
2  79  52  92
3  87  51  47
4  13  12   1
5  70  90  19
6  15  99   9
7  56  81  22
8  75  68  82
9  63  11  67
10 40  50  71
11 45  42  94
12 32  80  50
13 80  83  33
14  6  27   5
15 91 100  36
16 52  60  46
17 76   9   6
18 19   2  64
19 18  97  27
20 67   8  83

Finding The Column Means

Using colMeans function to find the column means −

 Live Demo

> x1<-sample(1:100,20)
> x2<-sample(1:100,20)
> x3<-sample(1:100,20)
> df<-data.frame(x1,x2,x3)
> colMeans(df)

Output

   x1    x2    x3
51.90 54.75 45.55

Subtracting column values from column means

Using data frame and column means of the data frame to subtract the column values from column means −

 Live Demo

> x1<-sample(1:100,20)
> x2<-sample(1:100,20)
> x3<-sample(1:100,20)
> df<-data.frame(x1,x2,x3)
> df[]-colMeans(df[])[col(df[])]

Output

     x1      x2     x3
1    2.1  18.25  11.45
2   27.1  -2.75  46.45
3   35.1  -3.75   1.45
4  -38.9 -42.75 -44.55
5   18.1  35.25 -26.55
6  -36.9  44.25 -36.55
7    4.1  26.25 -23.55
8   23.1  13.25  36.45
9   11.1 -43.75  21.45
10 -11.9  -4.75  25.45
11  -6.9 -12.75  48.45
12 -19.9  25.25   4.45
13  28.1  28.25 -12.55
14 -45.9 -27.75 -40.55
15  39.1  45.25  -9.55
16   0.1   5.25   0.45
17  24.1 -45.75 -39.55
18 -32.9 -52.75  18.45
19 -33.9  42.25 -18.55
20  15.1 -46.75  37.45

Updated on: 13-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements