问题描述
我在 mutate()
中有一个 case_when()
,我希望R停止并抛出如果满足 TRUE
条件,则为错误。这是出于调试目的。
I have a case_when()
inside a mutate()
and I'd like R to stop and throw an error if the TRUE
condition is fulfilled. This is for debugging purposes.
例如,mtcars $ cyl的值为4、6或8。在第四行有适当的解决方案后,这应该是能够正常运行:
For example, values for mtcars$cyl are 4, 6 or 8. With the proper solution in place in the fourth line, this should be able to run without error:
mtcars %>%
mutate(test = case_when(
cyl > 3 ~ "ok",
TRUE ~ # code for throwing error here
))
这应该引发错误:
mtcars %>%
mutate(test = case_when(
cyl < 3 ~ "ok",
TRUE ~ # code for throwing error here
))
我尝试了停止
,但这会触发异常,即使 TRUE
从未实现。
I tried stop
but this triggers the exception even if TRUE
is never fulfilled.
推荐答案
在 case_when
调用中,您无法执行此操作据我了解,因为所有RHS都会经过预先评估,以确保它们属于同一类型。
You can't do it in the case_when
call as far as I understand, because all RHSs will be evaluated beforehand to make sure they're of the same type.
但是您可以这样做:
mtcars %>%
mutate(test = case_when(
cyl > 3 ~ "ok",
TRUE ~ NA_character_
),
test=if (anyNA(test)) stop() else test
)
或
mtcars %>%
mutate(test = case_when(
cyl > 3 ~ "ok",
TRUE ~ "STOP_VALUE"
),
test=if ("STOP_VALUE" %in% test) stop() else test
)
这篇关于在case_when()中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!