data.table:减法级别表示从值 [英] data.table: Subtracting levels means from values

查看:118
本文介绍了data.table:减法级别表示从值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从 data.table 中的值减去级别平均值。我的MWE如下。任何帮助将高度赞赏。感谢

I wonder how to subtract levels means from values in data.table. My MWE is given below. Any help will be highly appreciated. Thanks

set.seed(12345)
A <- rep(x=paste0("A", 1:2), each=6)
B <- rep(x=paste0("B", 1:3), each=2, times=2)
Rep <- rep(x=1:2, times=3)
Y <- rnorm(n=12, mean = 50, sd = 5)

library(data.table)
dt <- data.table(A, B, Rep, Y)

dt[, j=mean(Y), by=.(A, B)]
dt[, j=mean(Y), by=.(A)]

dt[, j=mean(Y), by=.(A, B)] - dt[, j=mean(Y), by=.(A)]

Error in Ops.data.frame(dt[, j = mean(Y), by = .(A, B)], dt[, j = mean(Y),  : 
  ‘-’ only defined for equally-sized data frames

strong>已修改

Edited

其实我想要这个

dt[, j=mean(Y), by=.(A, B)] - dt[, j=mean(Y), by=.(A)] - dt[, j=mean(Y), by=.(B)] + dt[, j=mean(Y)]


推荐答案

你得到错误的原因是你减去的两个data.table的维度是不同的。另一方面,你可以使用 data.table code>:

The reason you get the error is the dimension of the two data.table you are subtracting is different. On the other hand, you can do a chained transformation using data.table:

dt[, j := mean(Y), .(A, B)][, j := j - mean(Y), .(A)]
dt
     A  B Rep        Y          j
 1: A1 B1   1 52.92764  3.6373822
 2: A1 B1   2 53.54733  3.6373822
 3: A1 B2   1 49.45348 -1.0071061
 4: A1 B2   2 47.73251 -1.0071061
 5: A1 B3   1 53.02944 -2.6302761
 6: A1 B3   2 40.91022 -2.6302761
 7: A2 B1   1 53.15049  0.1752053
 8: A2 B1   2 48.61908  0.1752053
 9: A2 B2   1 48.57920 -3.7182851
10: A2 B2   2 45.40339 -3.7182851
11: A2 B3   1 49.41876  3.5430798
12: A2 B3   2 59.08656  3.5430798

可以执行:

dt[, j := mean(Y), .(A, B)][, j := j - mean(Y), .(A)][, j := j - mean(Y), .(B)][, j := j + mean(Y)]
dt
     A  B Rep        Y         j
 1: A1 B1   1 52.92764  1.731088
 2: A1 B1   2 53.54733  1.731088
 3: A1 B2   1 49.45348  1.355590
 4: A1 B2   2 47.73251  1.355590
 5: A1 B3   1 53.02944 -3.086678
 6: A1 B3   2 40.91022 -3.086678
 7: A2 B1   1 53.15049 -1.731088
 8: A2 B1   2 48.61908 -1.731088
 9: A2 B2   1 48.57920 -1.355590
10: A2 B2   2 45.40339 -1.355590
11: A2 B3   1 49.41876  3.086678
12: A2 B3   2 59.08656  3.086678

这篇关于data.table:减法级别表示从值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆