[英]multiply dataframe columns with its parameters in another dataframe
I have parameters for 4 variables as shown below我有 4 个变量的参数,如下所示
parameters <- data.frame(param.x1 = 0.02,
param.x2 = 0.03,
param.x1.sq = 0.05,
param.x2.sq = 0.03)
I also have corresponding values of the 4 variables shown below我也有下面显示的4个变量的相应值
set.seed(123)
dat <- data.frame(
x1 = rnorm(5),
x2 = rnorm(5),
x1.sq = rnorm(5),
x2.sq = rnorm(5))
I want to multiply each variable by its corresponding parameter and then add the product as shown below我想将每个变量乘以其相应的参数,然后添加乘积,如下所示
final.val <- (dat$x1 * parameters$param.x1) +
(dat$x2 * parameters$param.x2) +
(dat$x1.sq * parameters$param.x1.sq) +
(dat$x2.sq * parameters$param.x2.sq)
How can I do this without typing the entire equation in case I have more than 4 variables?如果我有超过 4 个变量,我如何在不输入整个方程的情况下做到这一点? The order of my variables and parameters will always be same.我的变量和参数的顺序总是相同的。
We can use Map/Reduce
我们可以使用Map/Reduce
final.val2 <- Reduce(`+`, Map(`*`, dat, parameters))
Or use %*%
或使用%*%
final.val3 <- (as.matrix(dat) %*% unlist(parameters))[,1]
-checking with OP's output -检查 OP 的 output
identical(final.val, final.val2)
#[1] TRUE
identical(final.val, final.val3)
#[1] TRUE
Or another option with sweep/rowSums
或者使用sweep/rowSums
的另一个选项
rowSums(sweep(dat, 2, unlist(parameters), `*`))
You can try:你可以试试:
mapply(function(x,y) x*y,dat,parameters)
x1 x2 x1.sq x2.sq
[1,] -0.011209513 0.05145195 0.061204090 0.05360739
[2,] -0.004603550 0.01382749 0.017990691 0.01493551
[3,] 0.031174166 -0.03795184 0.020038573 -0.05899851
[4,] 0.001410168 -0.02060559 0.005534136 0.02104068
[5,] 0.002585755 -0.01336986 -0.027792057 -0.01418374
In practice you want to perform a matrix operation, therefore I would do the following:在实践中,您想要执行矩阵运算,因此我会执行以下操作:
c(as.matrix(dat)%*%t(as.matrix(parameters)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.