小编ema*_*oca的帖子

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

我在搜索指定传递给 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 提供服务。任何人都可以帮我解决这个问题吗?

r pipe dplyr across

1
推荐指数
1
解决办法
64
查看次数

标签 统计

across ×1

dplyr ×1

pipe ×1

r ×1