Suppose I have a data.table
with columns X1
,X2
,X3
,Y
. For each row, I would like to treat the entries in X1
,X2
,X3
as vector of length 3, take the inner product with a fixed vector say beta
of length 4, subtract the result from the entry inY
, square the result, and either output the final result for every row (or save it as another column).
After much research, I came up with this
dat[, (Y-sum(.SD*beta))^2, .SDcols=c(1:3)]
which does not work as expected.
Bonus point #1: Doing this with 3 replaced by a general n
.
Bonus point #2: Suppose I have a grp
column with group indices and I want to average these residual squares by group.