I have a datatable of data and a datatable of fitted coefficients. I want to calculate the fitted value for each row.
dt = data.table(a = rep(c("x","y"), each = 5), b = rnorm(10), c = rnorm(10), d = rnorm(10))
coefs = data.table(a = c("x","y"), b = c(0, 1), d = c(2,3))
dt
# a b c d
# 1: x -0.25174915 -0.2130797 -0.67909764
# 2: x -0.35569766 0.6014930 0.35201386
# 3: x -0.31600957 0.4398968 -1.15475814
# 4: x -0.54113762 -2.3497952 0.64503654
# 5: x 0.11227873 0.0233775 -0.96891456
# 6: y 1.24077566 -1.2843439 1.98883516
# 7: y -0.23819626 0.9950835 -0.17279980
# 8: y 1.49353589 0.3067897 -0.02592004
# 9: y 0.01033722 -0.5967766 -0.28536224
#10: y 0.69882444 0.8702424 1.24131062
coefs # NB no "c" column
# a b d
#1: x 0 2
#2: y 1 3
For each a=="x"
row in dt, I want 0*b+2*d
; and for each a=="y"
row in dt, I want 1*b+3*d
.
Is there a datatable way to do this without hardcode the column name? I'm happy to put the column names in a variable cols = colnames(coefs)[-1]
.
It's easy to loop over groups and rbind
together, so if the grouping is causing trouble, please ignore that part.