2

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
ddunn801
  • 1,900
  • 1
  • 15
  • 20
  • you're looking for `?rowSums` – eddi Aug 21 '15 at 18:15
  • 1
    This may be a dupe of my question: http://stackoverflow.com/q/19279075/1191259 I think @eddi 's answer there is good; I guess I should get around to accepting it. – Frank Aug 21 '15 at 19:15

2 Answers2

3

Using matrix multiplication:

coeffs <- as.vector(c(2,3,4))
dt2 <- DT[,Calc := as.matrix(DT[,..vars])%*%coeffs]
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Tchotchke
  • 3,061
  • 3
  • 22
  • 37
0

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
jlhoward
  • 58,004
  • 7
  • 97
  • 140