如何使用 dplyr 管道将额外参数传递给 purrr::map [英] How to pass extra parameter to purrr::map with dplyr pipe
问题描述
我有以下数据框和函数:
param_df <- data.frame(x = 1:3 + 0.1,y = 3:1 - 0.2)参数_df#>xy#>1 1.1 2.8#>2 2.1 1.8#>3 3.1 0.8my_function <- function(x, y, z) {x + y + z}
我想要做的是将 param_df
传递给 my_function
函数,但带有 param_df
中不包含的额外参数,例如 <代码>z=3.
我试过了,但失败了:
library(tidyverse)param_df %>%purrr::map(my_function, z =3 )
<块引用>
.f(.x[[i]], ...) 中的错误:缺少参数y",没有默认值
预期结果是一个包含三个值的列表,全部为:6.9
.
我知道我可以在 param_df
中插入 3
作为额外的列 z
.但这不是我想要的.因为在现实中,函数和 z
执行更复杂的计算.
我该怎么办?
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
另一种解决方案可能是:
map2(param_df$x, param_df$y, ~my_function(.x,.y,3))
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))
这篇关于如何使用 dplyr 管道将额外参数传递给 purrr::map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!