按组对data.frame执行基于矢量的操作 [英] Perform vector-based operation on data.frame by group
问题描述
我在这里看到了一些非常相似的问题,但是,我的大脑在将我直接读取的数据应用于数据时遇到了麻烦。
I have seen some fairly similar questions answered here, however, my brain is having some trouble making the leap to apply what I read directly to my data.
I想要从组织成组的较大数据框中减去data.frame中包含的向量。在这种情况下,我有一个标准参考(dfRef),我想从几个重复的实验测量值(dfMeasured)中减去以获得差值(dfDelta)的data.frame。
I would like to subtract a vector contained in a data.frame from a larger data frame that's organized into groups. In this scenario I have a standard reference (dfRef) that I would like to subtract from several repeated experimental measures (dfMeasured) to get a data.frame of the difference (dfDelta).
数据的组织方式如下:
dfRef
# input output
# 0 4
# 1 7
# 2 8
# 3 1
dfMeasured
# input output group
# 0 4 A
# 1 5 A
# 2 9 A
# 3 1 A
# 0 2 B
# 1 3 B
# 2 5 B
# 3 8 B
# 0 1 C
# 1 4 C
# 2 2 C
# 3 9 C
我希望输出为:
dfDelta
# input output group
# 0 0 A
# 1 -2 A
# 2 1 A
# 3 0 A
# 0 -2 B
# 1 -4 B
# 2 -3 B
# 3 7 B
# 0 -3 C
# 1 -3 C
# 2 -6 C
# 3 8 C
推荐答案
一种方法是在上连接
'input'和然后将值赋给'output
One way is join on
'input' and then assign the value to 'output
library(data.table)
setDT(dfMeasured)[dfRef, output := output - i.output,on = .(input)]
dfMeasured
# input output group
# 1: 0 0 A
# 2: 1 -2 A
# 3: 2 1 A
# 4: 3 0 A
# 5: 0 -2 B
# 6: 1 -4 B
# 7: 2 -3 B
# 8: 3 7 B
# 9: 0 -3 C
#10: 1 -3 C
#11: 2 -6 C
#12: 3 8 C
这篇关于按组对data.frame执行基于矢量的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!