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

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-14 15:06:43

问题


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?


回答1:


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))


来源:https://stackoverflow.com/questions/52308903/how-to-pass-extra-parameter-to-purrrmap-with-dplyr-pipe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!