Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass extra parameter to purrr::map with dplyr pipe

Tags:

r

tidyverse

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?

like image 526
scamander Avatar asked Jan 01 '23 21:01

scamander


1 Answers

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))
like image 167
AntoniosK Avatar answered Jan 05 '23 04:01

AntoniosK