在 data.table 中按组缩放 [英] scale by group in data.table
本文介绍了在 data.table 中按组缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按组会话"缩放 data.table 中的变量选择:
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
我试过了:
dt[,(2:3):=lapply(.SD,scale),by="session",.SDcols=2:3]
但我得到一个错误:
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?
推荐答案
scale
函数输出的是一个matrix
,所以转换成一个vector代码>
The scale
function output is a matrix
, so convert it to a vector
dt[, c("score1", "score2") := lapply(.SD, function(x) as.vector(scale(x))), by = session]
dt
# session score1 score2
# 1: 1 -0.7433155 -0.6859943
# 2: 1 -1.0530303 -1.0289917
# 3: 1 -0.2787433 -0.3429970
# 4: 1 0.8052585 0.6859944
# 5: 1 1.2698307 1.3719886
# 6: 2 -0.7847341 -0.6824535
# 7: 2 -0.2942753 -0.3650335
# 8: 2 -0.9949307 -0.9205191
# 9: 2 0.7567078 0.4285175
#10: 2 1.3172322 1.5394886
<小时>
为了更好地理解它,在一个简单的向量上尝试一下
To understand it better, try it on a simple vector
scale(1:10)
# [,1]
# [1,] -1.4863011
# [2,] -1.1560120
# [3,] -0.8257228
# [4,] -0.4954337
# [5,] -0.1651446
# [6,] 0.1651446
# [7,] 0.4954337
# [8,] 0.8257228
# [9,] 1.1560120
#[10,] 1.4863011
这篇关于在 data.table 中按组缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文