dplyr的mutate()
有异常处理机制吗?我的意思是一种捕获异常并处理它们的方法。
让我们假设我有一个函数在某些情况下会抛出错误(在示例中,如果输入为负),为了简单起见,我定义了该函数,但在现实生活中它将是某些情况下的函数R 包。让我们假设这个函数是向量化的:
# function throwing an error
my_func <- function(x){
if(x > 0) return(sqrt(x))
stop('x must be positive')
}
my_func_vect <- Vectorize(my_func)
现在,假设我想在 mutate()
中使用这个函数。
如果在 mutate()
中使用此函数,它将在第一个错误处停止并且不返回结果:
library(dplyr)
# dummy data
data <- data.frame(x = c(1, -1, 4, 9))
data %>% mutate(y = my_func_vect(x))
# Error in mutate_impl(.data, dots) : Evaluation error: x must be positive.
在这种情况下,有没有办法捕获错误并执行某些操作(例如返回 NA
),同时获取其他元素的结果?
我期望的结果是使用带有 tryCatch()
的循环所实现的结果,即类似于:
y <- rep(NA_real_, length(data$x))
for(i in seq_along(data$x)) {
tryCatch({
y[i] <- my_func_vect(data$x[i])
}, error = function(err){})
}
y
# Result is: 1 NA 2 4
最佳答案
我们还可以使用purrr
的safely()
或possously()
函数。
来自purrr
帮助:
safely: wrapped function instead returns a list with components result and error. One value is always NULL.
quietly: wrapped function instead returns a list with components result, output, messages and warnings.
possibly: wrapped function uses a default value (otherwise) whenever an error occurs.
它不会改变您必须分别将函数应用于每一行的事实。
library(dplyr)
library(purrr)
# function throwing an error
my_func <- function(x){
if(x > 0) return(sqrt(x))
stop('x must be positive')
}
my_func_vect <- Vectorize(my_func)
# dummy data
data <- data.frame(x = c(1, -1, 4, 9))
带有 map :
data %>%
mutate(y = map_dbl(x, ~possibly(my_func_vect, otherwise = NA_real_)(.x)))
#> x y
#> 1 1 1
#> 2 -1 NA
#> 3 4 2
#> 4 9 3
使用rowwise()
:
data %>%
rowwise() %>%
mutate(y = possibly(my_func_vect, otherwise = NA_real_)(x))
#> Source: local data frame [4 x 2]
#> Groups: <by row>
#>
#> # A tibble: 4 x 2
#> x y
#> <dbl> <dbl>
#> 1 1 1
#> 2 -1 NA
#> 3 4 2
#> 4 9 3
其他函数在“数据框架环境”中使用和应用有些困难,因为它们更适合使用列表并返回列表。
由reprex package于2018年5月15日创建(v0.2.0)。
关于r - 在 dplyr 的 mutate 中 try catch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334972/