在 dplyr 内部的自定义函数中指定参数时出现问题

ema*_*oca 1 r pipe dplyr across

我在搜索指定传递给 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))]
    )
  )
Run Code Online (Sandbox Code Playgroud)

这工作正常。然后我需要用自定义函数替换 lambda 函数,然后在内部传递请求的参数(在我的代码中自定义函数更复杂,并且嵌入到 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)
    )
  )
Run Code Online (Sandbox Code Playgroud)

R 现在给出错误“未找到对象‘Sepal.Length’”,因为它正在为管道进程内的对象而不是 colname 提供服务。任何人都可以帮我解决这个问题吗?

akr*_*run 5

我们可以使用cur_data()pick(来自 dplyr 的开发版本来选择列。此外,删除getget_which_max

\n
get_which_max <- function(x, col_max) x[which.max(col_max)]\n\niris_summary <- iris %>%\n  group_by(Species) %>%\n  summarise(\n    Sepal.Length_max = max(Sepal.Length),\n    across(\n      Sepal.Width:Petal.Width,\n      ~ get_which_max(.x, cur_data()[[ref_col]])\n    )\n  )\n
Run Code Online (Sandbox Code Playgroud)\n

-输出

\n
# A tibble: 3 \xc3\x97 5\n  Species    Sepal.Length_max Sepal.Width Petal.Length Petal.Width\n  <fct>                 <dbl>       <dbl>        <dbl>       <dbl>\n1 setosa                  5.8         4            1.2         0.2\n2 versicolor              7           3.2          4.7         1.4\n3 virginica               7.9         3.8          6.4         2  \n
Run Code Online (Sandbox Code Playgroud)\n