[英]Problem while specifiyng parameters in custom function inside dplyr's across
我在搜索以在自定义 function 中指定参数时遇到了一些麻烦,传递给 dplyr 中的.fns 参数。 考虑这段代码:
data(iris)
ref_col <- "Sepal.Length"
iris_summary <- iris %>%
group_by(Species) %>%
summarise(
Sepal.Length_max = max(Sepal.Length),
across(
Sepal.Width:Petal.Width,
~ .x[which.max(get(ref_col))]
)
)
这工作正常。 然后我需要用自定义的 function 替换 lambda function,然后在内部传递请求的 arguments(在我的代码中,自定义的 function 更复杂,嵌入到 dplyr 管道中并不方便)。 请参阅以下代码:
ref_col <- "Sepal.Length"
get_which_max <- function(x, col_max) x[which.max(get(col_max))]
iris_summary <- iris %>%
group_by(Species) %>%
summarise(
Sepal.Length_max = max(Sepal.Length),
across(
Sepal.Width:Petal.Width,
~ get_which_max(.x, ref_col)
)
)
R 现在给出错误“未找到对象‘Sepal.Length’”,因为它正在为 object 而不是管道进程中的 colname 服务。 谁能帮我解决这个问题?
我们可以使用cur_data()
或pick
(从 dplyr 的开发版本到 select 列。另外,从get_which_max
中删除get
get_which_max <- function(x, col_max) x[which.max(col_max)]
iris_summary <- iris %>%
group_by(Species) %>%
summarise(
Sepal.Length_max = max(Sepal.Length),
across(
Sepal.Width:Petal.Width,
~ get_which_max(.x, cur_data()[[ref_col]])
)
)
-输出
# A tibble: 3 × 5
Species Sepal.Length_max Sepal.Width Petal.Length Petal.Width
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 5.8 4 1.2 0.2
2 versicolor 7 3.2 4.7 1.4
3 virginica 7.9 3.8 6.4 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.