I would like to scale a selection of variables in data.table by group "session":
session score1 score2
1: 1 0.11111111 0.6000000
2: 1 0.00000000 0.5333333
3: 1 0.27777778 0.6666667
4: 1 0.66666667 0.8666667
5: 1 0.83333333 1.0000000
6: 2 0.07692308 0.5757576
7: 2 0.25641026 0.6363636
8: 2 0.00000000 0.5303030
9: 2 0.64102564 0.7878788
10: 2 0.84615385 1.0000000
I've tried:
dt[,(2:3):=lapply(.SD,scale),by="session",.SDcols=2:3]
But I get an error:
Error in `[.data.table`(dt, , `:=`((2:3), lapply(.SD, scale)), by = "session", :
All items in j=list(...) should be atomic vectors or lists. If you are trying something like j=list(.SD,newcol=mean(colA)) then use := by group instead (much quicker), or cbind or merge afterwards.
The code works but only without the grouping variable (session). What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…