如何编写也适用于 dplyr::across 的自定义函数?

发布于 2025-01-20 12:11:45 字数 1075 浏览 1 评论 0原文

我编写了一些自定义函数(请参阅下面的示例),这些函数在使用基本 R 和 dplyr::mutate 管道时都可以工作。然而,我很难让它与 dplyr::across 一起动态工作。

我做错了什么?

test1 <- function(data, column)
{
  if (!column %in% names(data))
  {
    stop("error in test1")
  }
  return(TRUE)
}

test2 <- function(data, column)
{
  check <- test1(data, column)
  
  if (check == TRUE)
  {
    my_sum <- sum(data[,column])
  }
  return(my_sum)
}

df <- data.frame(x = 1:5,
                 y = 11:15)

# Works    
test2(df, "x")

# Works
df |>
  dplyr::mutate(new_col = test2(df, "x"))

# Doesn't work
df |> 
  dplyr::mutate(across(c("x", "y"), ~test2(df, .)))

Error in `dplyr::mutate()`:
! Problem while computing `..1 = across(c("x", "y"), ~test2(df, .))`.
Caused by error in `across()`:
! Problem while computing column `x`.
Caused by error in `test1()`:
! error in test1
Run `rlang::last_error()` to see where the error occurred.
Warning message:
Problem while computing `..1 = across(c("x", "y"), ~test2(df, .))`.
i the condition has length > 1 and only the first element will be used 

I've written some custom functions (see examples below) that work when using both, base R and within a dplyr::mutate pipe. However, I struggle getting it working dynamically with dplyr::across.

What am I doing wrong?

test1 <- function(data, column)
{
  if (!column %in% names(data))
  {
    stop("error in test1")
  }
  return(TRUE)
}

test2 <- function(data, column)
{
  check <- test1(data, column)
  
  if (check == TRUE)
  {
    my_sum <- sum(data[,column])
  }
  return(my_sum)
}

df <- data.frame(x = 1:5,
                 y = 11:15)

# Works    
test2(df, "x")

# Works
df |>
  dplyr::mutate(new_col = test2(df, "x"))

# Doesn't work
df |> 
  dplyr::mutate(across(c("x", "y"), ~test2(df, .)))

Error in `dplyr::mutate()`:
! Problem while computing `..1 = across(c("x", "y"), ~test2(df, .))`.
Caused by error in `across()`:
! Problem while computing column `x`.
Caused by error in `test1()`:
! error in test1
Run `rlang::last_error()` to see where the error occurred.
Warning message:
Problem while computing `..1 = across(c("x", "y"), ~test2(df, .))`.
i the condition has length > 1 and only the first element will be used 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文