问题是:R锯
Sepal.Length, wt, len
符号,因此它尝试在当前环境中查找并评估它们。当然,它会导致错误,因为它们是数据帧的列。当您引用它们时,R并没有尝试评估并返回值,因为它将这些值视为字符串。
如果你替换
list
具有
base::alist
或
dplyr::vars
或
rlang::exprs
,应该有效
注意:由于我们已经对输入进行了报价,因此不需要使用
rlang::enquo
里面
tryfn
不再。
# loading the needed libraries
library(rlang)
library(tidyverse)
# defining the function
tryfn <- function(data, x, y) {
data <-
dplyr::select(
.data = data,
x = !! x,
y = !! y
)
# creating a data frame of means
result_df <- data.frame(mean.x = mean(data$x), mean.y = mean(data$y))
# return the data frame
return(result_df)
}
# alist handles its arguments as if they described function arguments.
# So the values are not evaluated, and tagged arguments with no value are
# allowed whereas list simply ignores them.
purrr::pmap(.l = list(
data = list(iris, mtcars, ToothGrowth),
x = alist(Sepal.Length, wt, len),
y = alist(Sepal.Width, mpg, dose)
),
.f = tryfn)
#> [[1]]
#> mean.x mean.y
#> 1 5.843333 3.057333
#>
#> [[2]]
#> mean.x mean.y
#> 1 3.21725 20.09062
#>
#> [[3]]
#> mean.x mean.y
#> 1 18.81333 1.166667
purrr::pmap(.l = list(
data = list(iris, mtcars, ToothGrowth),
x = dplyr::vars(Sepal.Length, wt, len),
y = dplyr::vars(Sepal.Width, mpg, dose)
),
.f = tryfn)
#> [[1]]
#> mean.x mean.y
#> 1 5.843333 3.057333
#>
#> [[2]]
#> mean.x mean.y
#> 1 3.21725 20.09062
#>
#> [[3]]
#> mean.x mean.y
#> 1 18.81333 1.166667
purrr::pmap(.l = list(
data = list(iris, mtcars, ToothGrowth),
x = rlang::exprs(Sepal.Length, wt, len),
y = rlang::exprs(Sepal.Width, mpg, dose)
),
.f = tryfn)
#> [[1]]
#> mean.x mean.y
#> 1 5.843333 3.057333
#>
#> [[2]]
#> mean.x mean.y
#> 1 3.21725 20.09062
#>
#> [[3]]
#> mean.x mean.y
#> 1 18.81333 1.166667
创建于2018-05-21
reprex package
(v0.2.0版)。