Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201919

Apply same function on same object, with different parameters -- the tidy way

$
0
0

I would like to apply iteratively the same function (in the example, my_function) to the same object (here, my_matrix) with different parameters (my_parameters) stored in a list, or something similar.

The reprex is:

library(tidyverse)
my_matrix <- replicate(10, sample(1:10, 10, replace = TRUE))
my_parameters <- tibble(value1 = sample(1:10, 5, replace = TRUE),
                        value2 = sample(2:3, 5, replace = TRUE))
my_function <- function(param1, param2, matrix) {
    (matrix + param1) * param2
}
new_matrix <- my_matrix
for (i in seq.int(nrow(my_parameters))) {
    new_matrix <- my_function(my_parameters$value1[[i]], my_parameters$value2[[i]], new_matrix)
}
new_matrix

(I guess I could compute everything in one iteration with a clever factorization, but this is just to illustrate the problem.)

Is there a tidy function, like:

magical_function(my_matrix, my_function, my_parameters)

that would do the trick?

So far, I dug into purrr, but accumulate, or similar functions, does not seem to apply here.

Of note, I am aware that factorization does not (directly) apply here, and that could explain why there is no obvious answer here (as far as I know).


Viewing all articles
Browse latest Browse all 201919

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>