如何用缺失值替换失败的目标?
How can I replace a failed target with a missing value?
我正在使用 drake 计划拟合一堆模型。其中一些由于初始化问题而失败。我是 运行 `make(plan, keep_going = T) 无论如何都要完成计划,但我真正想要的是能够跳过失败的目标并将它们视为缺失值在计划的其余部分。
有没有办法替换失败的目标,比如说一个常量 NA
符号?
编辑
这里有一个比我最初提供的例子更好的例子。您所需要的只是将您的模型包装在一个自定义函数中,该函数将失败转化为 NA
s.
library(drake)
fail_na <- function(code) {
tryCatch(code, error = error_na)
}
error_na <- function(e) {
NA
}
plan <- drake_plan(
failure = fail_na(stop()),
success = fail_na("success")
)
make(plan, keep_going = TRUE)
#> In drake, consider r_make() instead of make(). r_make() runs make() in a fresh R session for enhanced robustness and reproducibility.
#> target success
#> target failure
readd(failure)
#> [1] NA
readd(success)
#> [1] "success"
由 reprex package (v0.3.0)
于 2019-11-14 创建
原回答
这是可能的,但它需要一些自定义代码。下面,我们需要检查 x
是 NULL
还是缺失。
library(drake)
`%||%` <- function(x, y) {
if (is.null(x)) {
y
} else {
x
}
}
na_fallback <- function(x) {
out <- tryCatch(
x %||% NA,
error = function(e) {
NA
}
)
out
}
plan <- drake_plan(
x = stop(),
y = na_fallback(x)
)
make(plan, keep_going = TRUE)
#> In drake, consider r_make() instead of make(). r_make() runs make() in a fresh R session for enhanced robustness and reproducibility.
#> target x
#> fail x
#> target y
readd(y)
#> [1] NA
由 reprex package (v0.3.0)
于 2019-11-14 创建
我正在使用 drake 计划拟合一堆模型。其中一些由于初始化问题而失败。我是 运行 `make(plan, keep_going = T) 无论如何都要完成计划,但我真正想要的是能够跳过失败的目标并将它们视为缺失值在计划的其余部分。
有没有办法替换失败的目标,比如说一个常量 NA
符号?
编辑
这里有一个比我最初提供的例子更好的例子。您所需要的只是将您的模型包装在一个自定义函数中,该函数将失败转化为 NA
s.
library(drake)
fail_na <- function(code) {
tryCatch(code, error = error_na)
}
error_na <- function(e) {
NA
}
plan <- drake_plan(
failure = fail_na(stop()),
success = fail_na("success")
)
make(plan, keep_going = TRUE)
#> In drake, consider r_make() instead of make(). r_make() runs make() in a fresh R session for enhanced robustness and reproducibility.
#> target success
#> target failure
readd(failure)
#> [1] NA
readd(success)
#> [1] "success"
由 reprex package (v0.3.0)
于 2019-11-14 创建原回答
这是可能的,但它需要一些自定义代码。下面,我们需要检查 x
是 NULL
还是缺失。
library(drake)
`%||%` <- function(x, y) {
if (is.null(x)) {
y
} else {
x
}
}
na_fallback <- function(x) {
out <- tryCatch(
x %||% NA,
error = function(e) {
NA
}
)
out
}
plan <- drake_plan(
x = stop(),
y = na_fallback(x)
)
make(plan, keep_going = TRUE)
#> In drake, consider r_make() instead of make(). r_make() runs make() in a fresh R session for enhanced robustness and reproducibility.
#> target x
#> fail x
#> target y
readd(y)
#> [1] NA
由 reprex package (v0.3.0)
于 2019-11-14 创建