如何编写也适用于 dplyr::across 的自定义函数?
我编写了一些自定义函数(请参阅下面的示例),这些函数在使用基本 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论