我有以下数据框
library(tidyverse)
param_df <- data.frame(
y_high = 10:12,
x = 1:3 + 0.1,
y = 3:1 - 0.1,
z = letters[1:3]
) %>%
as.tibble() %>%
mutate(z = as.character(z))
param_df
#> # A tibble: 3 x 4
#> y_high x y z
#> <int> <dbl> <dbl> <chr>
#> 1 10 1.10 2.90 a
#> 2 11 2.10 1.90 b
#> 3 12 3.10 0.900 c
以下功能
myfunc <- function(x=NULL, y=NULL, z=NULL) {
# The function is simpy printing the sum
cat(" The sum of ", z ," is ", x + y , "\n")
}
该功能的作用是仅从x
中获取y
和param_df
列,然后只打印总和。
我试过这个
param_df %>%
purrr::pmap(myfunc, x = x, y = y, z=z)
# # Later would like to have the flexibility to do
# param_df %>%
# purrr::pmap(myfunc, x = x, y = y_high, z=z)
但它提供了以下错误消息:
Error in .f(x = .l[[c(1L, i)]], y = .l[[c(2L, i)]], z = .l[[c(3L, i)]], :
formal argument "x" matched by multiple actual arguments
做正确的方法是什么?
purrr::pmap
所需的最终输出是
The sum a is 4
The sum b is 4
The sum c is 4
答案 0 :(得分:2)
您的功能只有副作用,因此您需要walk
而不是map
。
walk2
将采用2个参数并应用函数。
purrr::walk2(param_df$x, param_df$y, myfunc)
# The sum is 4
# The sum is 4
# The sum is 4
编辑: 以你为榜样。
myfunc <- function(x=NULL, y=NULL, z=NULL) {
# The function is simpy printing the sum
cat(" The sum of ", z ," is ", x + y , "\n")
}
param_df %>%
with(
pwalk(list(x, y, z), .f = myfunc))
# The sum of a is 4
# The sum of b is 4
# The sum of c is 4
或者,使用magrittr
特殊管道。
library('magrittr')
param_df %$%
pwalk(list(x, y, z), .f = myfunc)
# The sum of a is 4
# The sum of b is 4
# The sum of c is 4