Syntax error How to standardize selected columns in data.table object in R?

How to standardize selected columns in data.table object in R?



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

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

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

Example

Create the data.table object

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

library(data.table)
var1<-sample(1:10,25,replace=TRUE)
var2<-sample(1:10,25,replace=TRUE)
var3<-sample(1:10,25,replace=TRUE)
DT<-data.table(var1,var2,var3)
DT

Output

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

    var1 var2 var3
1:   8   10    3
2:  10    7    2
3:   2    8    2
4:   1    8    5
5:   5    7    6
6:   2    7   10
7:   7    6    2
8:   7    3    8
9:   4    2    9
10:  6    2   10
11:  8    8    9
12:  8    9    7
13:  1    9   10
14:  7    8    1
15:  4    6    5
16:  9    6    1
17: 10    2    5
18: 10    5    6
19:  5    6    2
20:  4    6   10
21:  5    9   10
22:  7    6    4
23:  3    5    4
24:  7    2    6
25:  1    2    3
    var1 var2 var3

Standardize selected columns

Using scale function and cbind function with subsetting to standardize columns 2 and 3 in data.table object DT −

library(data.table)
var1<-sample(1:10,25,replace=TRUE)
var2<-sample(1:10,25,replace=TRUE)
var3<-sample(1:10,25,replace=TRUE)
DT<-data.table(var1,var2,var3)
DT[]<-cbind(DT[,1],scale(DT[,2:3]))
DT

Output

     var1    var2        var3
1:   8   1.60028763  -0.8187877
2:  10   0.41195523  -1.1337060
3:   2   0.80806603  -1.1337060
4:   1   0.80806603  -0.1889510
5:   5   0.41195523   0.1259673
6:   2   0.41195523   1.3856406
7:   7   0.01584443  -1.1337060
8:   7  -1.17248797   0.7558040
9:   4  -1.56859877   1.0707223
10:  6  -1.56859877   1.3856406
11:  8   0.80806603   1.0707223
12:  8   1.20417683   0.4408857
13:  1   1.20417683   1.3856406
14:  7   0.80806603  -1.4486243
15:  4   0.01584443  -0.1889510
16:  9   0.01584443  -1.4486243
17: 10  -1.56859877  -0.1889510
18: 10  -0.38026637   0.1259673
19:  5   0.01584443  -1.1337060
20:  4   0.01584443   1.3856406
21:  5   1.20417683   1.3856406
22:  7   0.01584443  -0.5038693
23:  3  -0.38026637  -0.5038693
24:  7  -1.56859877   0.1259673
25:  1  -1.56859877  -0.8187877
    var1    var2          var3
Updated on: 2021-11-08T10:36:05+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements