89_Simple
89_Simple

Reputation: 3805

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.

Upvotes: 0

Views: 32

Answers (3)

carlo_sguera
carlo_sguera

Reputation: 395

In practice you want to perform a matrix operation, therefore I would do the following:

c(as.matrix(dat)%*%t(as.matrix(parameters)))

Upvotes: 1

Duck
Duck

Reputation: 39613

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

Upvotes: 1

akrun
akrun

Reputation: 887691

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), `*`))

Upvotes: 1

Related Questions