简体   繁体   中英

multiply dataframe columns with its parameters in another dataframe

I have parameters for 4 variables as shown below

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

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? The order of my variables and parameters will always be same.

We can use Map/Reduce

final.val2 <- Reduce(`+`, Map(`*`, dat, parameters))

Or use %*%

final.val3 <- (as.matrix(dat) %*% unlist(parameters))[,1]

-checking with OP's output

identical(final.val, final.val2)
#[1] TRUE

identical(final.val, final.val3)
#[1] TRUE

Or another option with 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM