I am looking for the R way (preferably "Tidyverse way") to map a function to multiple arguments.
I have created a function with multiple arguments:
product <- function(a = 1, b = 2, c = 3, d = 4){
return(c(a, b, c, d, a*b*c*d))
}
I am looking for the most convenient way to use the function multiple times with different parameters. I am able to use the map
functions from the purrr
package (to some extent), but there are two scenarios in which I am stuck:
1) If I only want to alter c
2) If I want to alter for example c
and d
*
My solution is rather cumbersome. I either create a wrapper around the function for my specific needs (so a lot of wrappers...) or use the pmap
function from the purrr
package, e.g.:
a <- list(1, 1, 1, 1, 1)
b <- list(2, 2, 2, 2, 2)
c <- list(1, 2, 3, 4, 5)
d <- list(4, 4, 4, 4, 4)
pmap(list(a, b, c, d), product)
Is there a better way to solve this?
Does this help?
If you only want to change c
map(1:4, product, a = 1, b = 2, d = 4)
If you only want to change c
and d
pmap(list(1:4, 11:14), product, a = 1, b = 2)
And a suggestion: don't use c
as an object name. c
is the function that creates a vector. Something else is better coding style.