rapplypurrrfurrr

Pass data.frame row-wise to function using purrr/furrr instead of apply


Question::

What is the equivalent purrr/furrr function for apply, which takes a data-frame and row-wise feeds it to a function?

Context::

I have a data.frame of parameter combinations:

n=10

parameters <- data.frame(
lam = runif(n = n, min = .35, max = .5),
# cs = runif(n = n, min = 1.3, max = 2.5),
cs = rnorm(n = n, mean = 1.18, sd = 0.15),
af = runif(n = n, min = 1.5, max = 2.2)
)

I have a function that takes values from the parameters data.frame and produces a vector.

gradient_model <- function(parameters) {
lam <- parameters[1]
cs <- parameters[2]
af <- parameters[3]
x <- rep(0, 5)

    for (i in seq(1, 5)) {
        x[i + 1] <- x[i] + lam * (cs * af - x[i])
    }
  return(x %>% unlist())
}

Currently I'm using apply but can't find the equivalent purrr (and hence furrr for parallel) command

For every row of parameters run the recurrence function gradientModel and store the results in a data.frame

predictions <- apply(parameters, 1, gradient_model)

What is the equivalent purrr/furrr function?


Solution

  • pmap*() (and hence future_pmap*()) matches arguments by names, so you could do:

    pmap_dfc(parameters, 
             function(lam, cs, af) {
                 x <- rep(0, 5)
                 
                 for (i in seq(1, 5)) {
                     x[i + 1] <- x[i] + lam * (cs * af - x[i])
                 }
                 return(x)
             }) 
    
       ...1  ...2  ...3  ...4  ...5  ...6  ...7  ...8  ...9 ...10
      <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    1 0     0      0    0     0     0     0      0    0     0    
    2 0.866 0.701  1.04 0.809 0.845 0.885 0.988  1.00 0.760 0.995
    3 1.33  1.12   1.57 1.29  1.37  1.34  1.56   1.53 1.16  1.56 
    4 1.57  1.37   1.84 1.59  1.70  1.57  1.89   1.81 1.36  1.88 
    5 1.71  1.52   1.98 1.76  1.91  1.69  2.08   1.95 1.47  2.06 
    6 1.78  1.61   2.05 1.86  2.03  1.76  2.19   2.03 1.53  2.16