我使用across()
,我想把NA
放在计算失败的地方。我试图使用tryCatch()
,但不能使它在我的情况下工作,而有些情况下,它的工作。
如此:
library(dplyr)
head(mtcars) %>%
mutate(
across(
all_of("drat"),
function(x) tryCatch(blabla, error = function(e) NA) # create an intentional error for the example
)
)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 NA 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 NA 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 NA 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 NA 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 NA 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 NA 3.460 20.22 1 0 3 1
但这不是:
library(dplyr)
head(mtcars) %>%
mutate(
across(
all_of("drat"),
function(x) tryCatch(x[which(mpg == 10000)], error = function(e) NA) # create an intentional error for the example
)
)
#> Error in `mutate()`:
#> ! Problem while computing `..1 = across(...)`.
#> Caused by error in `across()`:
#> ! Problem while computing column `drat`.
在2022-07-07由reprex包(v2.0.1)创建
我认为tryCatch()
应该捕捉任何错误。为什么在第二种情况下不起作用?如何解决这个问题?
注意:我需要在我的实际情况下使用across()
(即使它在示例中并不真正需要)
问题不是tryCatch
,因为您运行的代码不会触发错误。基本上你在运行
foo <- function(x) tryCatch(x[which(mtcars$mpg==10000)], error = function(e) NA))
foo(mtcars$drat)
# numeric(0)
注意没有触发错误。该表达式只是返回numeric(0)
。问题是这个函数需要返回一个长度非零的值。因此,在您的tryCatch
代码运行后发生错误,并且dplyr试图将值分配回data.frame。您需要处理没有单独找到值的情况。也许
head(mtcars) %>%
mutate(
across(
all_of("drat"),
function(x) {
matches <- mpg == 10000
if (any(matches)) x[which(matches)] else NA
}
)
)
看起来你只需要引用mpg
与x
:
library(dplyr)
head(mtcars) %>%
mutate(
across(
all_of("drat"),
function(x) tryCatch(x[which(x$mpg == 10000)], error = function(e) NA) # create an intentional error for the example
)
)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 NA 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 NA 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 NA 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 NA 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 NA 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 105 NA 3.460 20.22 1 0 3 1