I have the following data frame and function:
param_df <- data.frame(
x = 1:3 + 0.1,
y = 3:1 - 0.2
)
param_df
#> x y
#> 1 1.1 2.8
#> 2 2.1 1.8
#> 3 3.1 0.8
my_function <- function(x, y, z) {
x + y + z
}
What I want to do is to pass param_df
to my_function
function but with extra parameters which don't contain in param_df
, say z=3
.
I tried this but failed:
library(tidyverse)
param_df %>%
purrr::map(my_function, z =3 )
Error in .f(.x[[i]], ...) : argument "y" is missing, with no default
The expected result is a list with three values, all: 6.9
.
I know I can insert 3
in param_df
as extra column z
.
But that's not I want. Because in reality, the function and z
perform more complex calculation.
How can I go about it?
library(tidyverse)
param_df <- data.frame(
x = 1:3 + 0.1,
y = 3:1 - 0.2
)
my_function <- function(x, y, z) {
x + y + z
}
param_df %>% pmap(~my_function(.x,.y,3))
# [[1]]
# [1] 6.9
#
# [[2]]
# [1] 6.9
#
# [[3]]
# [1] 6.9
Another solution could be:
map2(param_df$x, param_df$y, ~my_function(.x,.y,3))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With