data.table“ sumproduct”样式矢量乘法 [英] data.table "sumproduct" style vector multiplication

查看:55
本文介绍了data.table“ sumproduct”样式矢量乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个玩具示例中,我想用每行各自的值求和一个系数列表,并将结果分配给新列。下面的代码适用于给定的记录,但是当我删除i参数时,它对我而言表现异常。我可以循环执行或应用,但似乎缺少一种data.table方式。

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


推荐答案

使用矩阵乘法:

coeffs <- as.vector(c(2,3,4))
dt2 <- DT[,Calc := as.matrix(DT[,..vars])%*%coeffs]

这篇关于data.table“ sumproduct”样式矢量乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆