Home > OS >  Using purrr to connect a dataframe of parameters with a dataframe of coefficients
Using purrr to connect a dataframe of parameters with a dataframe of coefficients

Time:04-26

I have a dataframe of coefficients and a dataframe of parameters. Example:

coefficients <- data.frame(a   = c(1, 2, 3),
                           b_w = c(3, 4, 5),
                           b_x = c(5, 6, 7))

parameters <- data.frame(w = c(0, 1),
                         x = c(2, 3))

I want to generate a dataframe by multiplying these two data frames for all combinations of coefficients and parameters, in which each column is numbered based on the relevant row number in the parameters dataframe. Example:


output <- data.frame(
  params1 = c(coefficients$a[1]   coefficients$b_w[1]*parameters$w[1]   coefficients$b_x[1]*parameters$x[1],
              coefficients$a[2]   coefficients$b_w[2]*parameters$w[1]   coefficients$b_x[2]*parameters$x[1],
              coefficients$a[3]   coefficients$b_w[3]*parameters$w[1]   coefficients$b_x[3]*parameters$x[1]),
  params2 = c(coefficients$a[1]   coefficients$b_w[1]*parameters$w[2]   coefficients$b_x[1]*parameters$x[2],
              coefficients$a[2]   coefficients$b_w[2]*parameters$w[2]   coefficients$b_x[2]*parameters$x[2],
              coefficients$a[3]   coefficients$b_w[3]*parameters$w[2]   coefficients$b_x[3]*parameters$x[2]
  )            
)

It seems to me that this must be possible using purrr, but I cannot figure out how to get started.

CodePudding user response:

You can use matrix multiplication here:

coefs <- as.matrix(coefficients)
params <- as.matrix(parameters)


out <- coefs %*% t(cbind(1, params))
colnames(out) <- paste0("params", 1:2)
out
#     params1 params2
#[1,]      11      19
#[2,]      14      24
#[3,]      17      29

CodePudding user response:

@markus provides an elegant matrix-based solution, but (as per the question title) I am looking for a purrr-based solution. I still haven't found one, but I do have a solution that remains within the tidyverse:

library(tidyverse)
parameters %>% 
  mutate(params = row_number()) %>% 
  crossing(coefficients) %>% 
  mutate(output = a   b_w*w   b_x*x) %>% 
  select(params, output) %>% 
  pivot_wider(names_from = params,
              names_prefix = "params",
              values_from = output,
              values_fn = list) %>% 
  unnest(cols = everything())
  • Related