考虑以下两个数据表:
x <- data.table(id=c(1,2,3,4),cost=c(0.7,0.2,0.5,0.9))
y <- data.table(id=c(1,2,3,4),group=c(1,2,1,2))
setkey(x,id)
setkey(y,id)
我想通过减去按 y 中的组分组的平均值来标准化成本。
我的尝试如下,但是,R 给出了找不到“组”的错误:
x[y,cost:=(cost-mean(cost)),by=.(group)]
有没有一种不向 x 添加列的情况下执行此操作的好方法?
最佳答案
这对你有用吗?
output <- y[x][, normcost:=(cost-mean(cost)), by=group]
output
# id group cost normcost
# 1: 1 1 0.7 0.10
# 2: 2 2 0.2 -0.35
# 3: 3 1 0.5 -0.10
# 4: 4 2 0.9 0.35
关于r - data.table 按连接表中的非 id 列分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37285184/