Perform vector-based operation on data.frame by gr

2020-04-18 05:25发布

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 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).

The data is organized as such:

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

I would like my output to be something like:

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

1条回答
家丑人穷心不美
2楼-- · 2020-04-18 06:07

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
查看更多
登录 后发表回答