想要根据每个组内的级别计算值。比如说,(a - b) / c
,然后为结果创建一个新列。
library(data.table)
DT =data.table(Group=rep(LETTERS[1:3], each=3),
level=rep(letters[1:3],3),
value=sample(100,9))[order(Group)]
# Group level value
# 1: A a 78
# 2: A b 10
# 3: A c 94
# 4: B a 68
# 5: B b 76
# 6: B c 46
# 7: C a 100
# 8: C b 54
# 9: C c 55
DT[,Result:=(DT[level=="a", .(value), by=.(Group,level)]$value -
DT[level=="b", .(value), by=.(Group,level)]$value) /
DT[level=="c", .(value), by=.(Group,level)]$value]
# Group level value Result
# 1: A a 78 0.7234043
# 2: A b 10 -0.1739130
# 3: A c 94 0.8363636
# 4: B a 68 0.7234043
# 5: B b 76 -0.1739130
# 6: B c 46 0.8363636
# 7: C a 100 0.7234043
# 8: C b 54 -0.1739130
# 9: C c 55 0.8363636
必须以一些优雅的方式在data.table中执行此操作。 请指教,谢谢