问题
In this toy example, I want to "sumproduct" a list of coefficients with each row's respective value and assign the result to a new column. The code below works for a given record, but when I remove the i parameter it behaves unexpectedly to me. I could do this in a loop or apply, but it seems like there's a data.table way that I'm missing.
DT <- data.table(mtcars)
vars <- c("mpg","cyl","wt")
coeffs <- c(2,3,4)
DT[1,Calc := sum(coeffs*DT[1,vars,with=FALSE])] # row 1 is assigned 70.480
DT[,Calc := sum(coeffs*DT[,vars,with=FALSE])] # all rows assigned 2830.416
回答1:
Using matrix multiplication:
coeffs <- as.vector(c(2,3,4))
dt2 <- DT[,Calc := as.matrix(DT[,vars,with=FALSE])%*%coeffs]
回答2:
Here's another way, but I guess it uses an apply(...)
based method, so this may not be what you're looking for.
DT[,Calc:=rowSums(mapply("*",DT[,vars,with=FALSE],coeffs))]
DT[1:3]
# mpg cyl disp hp drat wt qsec vs am gear carb Calc
# 1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 70.48
# 2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 71.50
# 3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 66.88
来源:https://stackoverflow.com/questions/32146456/data-table-sumproduct-style-vector-multiplication