Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scale in data.table in r

       LC  RC TOEIC eua again  class
   1: 490 390   880  90     0 100818
   2: 495 395   890  90     0 100818
   3: 490 330   820  90     0 100818
   4: 495 460   955  96     0 100818
   5: 495 370   865  91     0 100818
  ---                               
1021: 470 400   870  61     0 100770
1022: 260 180   440  48     0 100770
1023: 345 190   535  39     0 100770
1024: 450 295   745  65     0 100770
1025: 395 230   625  79     0 100770

This data.table is named "analy"

I want to scale the variables "LC","RC","TOEIC","eua". I can scale as below

analy[,LC:=scale(LC)]
analy[,RC:=scale(RC)]
analy[,TOEIC:=scale(TOEIC)]
analy[,eua:=scale(eua)]

but, I want to know how to scale the variables at once.

like image 708
Rokmc1050 Avatar asked Dec 01 '22 19:12

Rokmc1050


1 Answers

analy[ , c("LC", "RC", "TOEIC", "eua") := lapply(list(LC, RC, TOEIC, eua), scale)] 

A little more convenient way of doing it would be (as @David mentions under comment):

cols <- c("LC", "RC", "TOEIC", "eua")
analy[, (cols) := lapply(.SD, scale), .SDcols=cols]

Note the ( around cols is necessary so that cols is evaluated to get the column names, and then modify them by reference. This is so that we can still continue doing: DT[ ,col := val].

like image 140
asb Avatar answered Dec 05 '22 11:12

asb