Syntax error How to standardize multiple columns not all in data.table object in R?

How to standardize multiple columns not all in data.table object in R?



To standardize multiple columns not all in data.table object in R, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, subset the columns with single square brackets and use lapply, list and scale function to standardize those columns.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,25)
DT<-data.table(x,y,z)
DT

Output

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

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

Standardize multiple columns not all

Subset the x and y columns with single square brackets and use lapply, list and scale function to standardize those columns as shown below −

library(data.table)
x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,25)
DT<-data.table(x,y,z)
DT[,c("y","z"):=lapply(list(y,z),scale)]
DT

Output

      x       y       z
1:   31 -0.6845293  1.3518818
2:    4  0.6212997  1.0579944
3:   25  1.1711225  0.9110508
4:   21  1.1023946  0.1028606
5:   50  1.3085782 -1.2196325
6:   48 -1.4405357  1.4253536
7:   32  0.2776605 -0.9257451
8:   36 -0.6158015  0.8375789
9:   15 -0.7532572  1.2049381
10:  49  0.9649390 -0.8522733
11:  30 -0.5470737  0.3967479
12:  10  0.4151162 -0.4849141
13:  47 -1.0281686 -0.2644986
14:   1  1.2398503 -0.7053296
15:   5  0.2089327  0.2498042
16:  20 -0.2034344 -0.0440831
17:  42 -0.9594407 -1.7339353
18:  26 -1.8529027  0.1763324
19:  33  0.8274833 -0.5583860
20:  22  0.8962111  1.2784099
21:  44 -1.3718078 -1.5135198
22:  23 -1.5092635  1.1314663
23:  28  0.7587554 -1.6604635
24:  16  0.1402048 -0.6318578
25:   9  1.0336668  0.4702197
     x       y         z
Updated on: 2021-11-12T05:27:52+05:30

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements