How to standardize selected columns in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To standardize selected columns in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use scale function with subsetting to standardize selected columns.

Example

Create the data frame

Let’s create a data frame as shown below −

v1<-sample(1:50,25)
v2<-sample(1:50,25)
v3<-sample(1:50,25)
v4<-sample(1:50,25)
df<-data.frame(v1,v2,v3,v4)
df

Output

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

   v1 v2 v3 v4
1  10  4 39 13
2  16  1 49 12
3   9 48  4 43
4  40  5 33  2
5  17 45 37 47
6  49 12  6 36
7  13 37 35  8
8  38  8 13 10
9  33 33  2 15
10 41 26 17 46
11 27 18 24 16
12  6 44 19 50
13  2 46 18  6
14 35 29 10  5
15 24 43  1 48
16 32 35  9 35
17 19 49 21  3
18  3 50 28  1
19 36 24  5 11
20 26 38 30 33
21 31 13 48 40
22 11  2 46 26
23  1 34 43 28
24  4  3 12 24
25 46 25 26 45

Standardize selected columns

Using scale function with subsetting to standardize columns 1 and 2 in data frame df −

v1<-sample(1:50,25)
v2<-sample(1:50,25)
v3<-sample(1:50,25)
v4<-sample(1:50,25)
df<-data.frame(v1,v2,v3,v4)
df[,1:2]<-scale(df[,1:2])
df

Output

      v1           v2       v3 v4
1   1.19292168  1.31487197  10 39
2  -0.83728541  0.55041152  35 15
3   1.40294311 -0.53257411  13  4
4   0.49285027  0.04077122   1  1
5  -0.27722828  1.06005182  16 10
6   0.84288598 -0.65998418  34 19
7   0.14281457 -0.46886907  45 36
8  -1.60736396  0.99634678   6  7
9   0.98290026  1.25116693  32 47
10  0.07280743  0.93264174  14 30
11 -1.39734254  0.23188634  42 16
12  1.12291454 -1.48814967  20 50
13 -1.32733540  0.74152663   4 33
14  1.54295739 -0.40516404  30 46
15  0.21282171 -0.78739426  48 27
16  0.28282885 -1.74296982  36 37
17 -0.20722114  0.67782160   9  6
18  0.70287170 -0.85109930  26 26
19 -1.53735682 -1.42444463  19  5
20 -0.76727827  1.18746189  21 23
21 -1.11731397 -0.08663885  18 35
22 -0.69727113 -1.67926478  11  9
23 -0.90729255  0.35929641  25 42
24  1.26292883 -0.59627915   7 12
25  0.42284313  1.37857700  47 40
raja
Published on 11-Nov-2021 06:28:17
Advertisements