假设我有以下的`data.table`数据表:
我正在尝试查找bin和变量之间的平均差异:
如何改进这段代码?请注意每个变量都有不同的用户指定间隔。
library(data.table)
dt <- data.table(x1 = c(1:12), x2=c(21:32))
然后,我使用以下方法按照用户指定的间隔创建箱子:
dt[,intx1:=cut(x1, breaks = c(-Inf, 4, 9, Inf))]
返回,
x1 x2 intx1
1: 1 21 (-Inf,4]
2: 2 22 (-Inf,4]
3: 3 23 (-Inf,4]
4: 4 24 (-Inf,4]
5: 5 25 (4,9]
6: 6 26 (4,9]
7: 7 27 (4,9]
8: 8 28 (4,9]
9: 9 29 (4,9]
10: 10 30 (9, Inf]
11: 11 31 (9, Inf]
12: 12 32 (9, Inf]
我正在尝试查找bin和变量之间的平均差异:
dt[, mux1_grp:=mean(x1), by = intx1][,mux1_pop:=mean(x1)][,mux1_diff:=mux1_grp-mux1_pop]
dt[,`:=`(intx1=NULL, mux1_grp=NULL, mux1_pop=NULL)]
返回结果如下:
x1 x2 mux1_diff
1: 1 21 -4.0
2: 2 22 -4.0
3: 3 23 -4.0
4: 4 24 -4.0
5: 5 25 0.5
6: 6 26 0.5
7: 7 27 0.5
8: 8 28 0.5
9: 9 29 0.5
10: 10 30 4.5
11: 11 31 4.5
12: 12 32 4.5
然而,我的原始数据包含多个变量(例如,x1、x2、...、x20)。
因此,我需要按照以下步骤重复x2的相同程序:
dt[,intx2:=cut(x2, breaks = c(-Inf, 25, 28, Inf))]
dt[, mux2_grp:=mean(x2), by = intx2][,mux2_pop:=mean(x2)][,mux2_diff:=mux2_grp-mux2_pop]
dt[,`:=`(intx2=NULL, mux2_grp=NULL, mux2_pop=NULL)]
我的最终输出将是:
x1 x2 mux1_diff mux2_diff
1: 1 21 -4.0 -3.5
2: 2 22 -4.0 -3.5
3: 3 23 -4.0 -3.5
4: 4 24 -4.0 -3.5
5: 5 25 0.5 -3.5
6: 6 26 0.5 0.5
7: 7 27 0.5 0.5
8: 8 28 0.5 0.5
9: 9 29 0.5 4.0
10: 10 30 4.5 4.0
11: 11 31 4.5 4.0
12: 12 32 4.5 4.0
如何改进这段代码?请注意每个变量都有不同的用户指定间隔。
for
循环,因为分组变量每次都会改变。 - akrundt[,\
:=`(int=NULL, mu_grp=NULL, mu_pop=NULL)]可以写成
dt[,c("int","mu_grp","mu_pop") := NULL]。关于你实际的问题,我建议使用
melt` 将 x1..x20 放在单个列中,并转换为长格式。这在第五篇文献中有介绍:https://github.com/Rdatatable/data.table/wiki/Getting-started - Frank