R语言 条件处理
决策处理或条件处理是任何编程语言中的一个重要点。大多数的用例都会产生积极或消极的结果。有时,有可能对不止一种可能性进行条件检查,它有n种可能性。在这篇文章中,让我们讨论一下R语言中的条件处理是如何工作的。
沟通潜在的问题
开发人员总是写好的代码以达到好的结果。不是所有的问题都是意料之外的。一些预期的潜在问题是。
- 为一个变量提供了错误的输入类型。在数字的位置上,我们给出了字母数字值。
- 在上传文件时,在提到的位置不存在一个文件。
- 计算某些数值后的输出结果被认为是数字,但原始输出是空的或空的或无效的。
在这些情况下,R代码有可能出错。通过错误、警告和信息,它们可以被传达。致命的错误由 stop() 产生,并强制终止所有的执行。 当一个函数没有办法继续时,就会使用 错误 。警告由 warning() 产生,用于显示潜在的问题,例如当一个矢量输入的某些元素无效时,如log(-1:2)。消息是由 message() 生成的,用于以一种用户可以轻易抑制的方式给出信息性输出。
以编程方式处理条件
在R语言中,有三种不同的工具,用于以编程方式处理包括错误在内的条件。 try() 使你能够在发生错误时继续执行。
例
success <- try(100 + 200)
failure <- try("100" + "200")
输出
Error in "100" + "200" : non-numeric argument to binary operator
# Class of success
class(success)
[1] "numeric"
# Class of failure
class(failure)
[1] "try-error"
当我们把代码放在try块中时,代码就会执行,即使发生错误,对于正确的结果,它将是最后评估的结果,如果失败,它将给出 “try-error “。 tryCatch() 指定了处理函数,控制当条件发出信号时发生什么。 人们可以对警告、信息和中断采取不同的行动。
示例
# Using tryCatch()
display_condition <- function(inputcode)
{
tryCatch(inputcode,
error = function(c) "Unexpected error occurred",
warning = function(c) "warning message, but
still need to look into code",
message = function(c) "friendly message, but
take precautions")
}
# Calling the function
display_condition(stop("!"))
display_condition(warning("?!"))
display_condition(message("?"))
display_condition(10000)
For Input:
display_condition(stop(“!”))
Output:
[1] “Unexpected error occurred”
For Input:
display_condition(warning(“?!”))
Output:
[1] “warning message, but still need to look into code”
For Input:
display_condition(message(“?”))
Output:
[1] “friendly message, but take precautions”
For Input:
display_condition(10000)
Output:
[1] 10000
withCallingHandlers() 是 tryCatch() 的一个替代品 。 它建立了本地的处理程序,而 tryCatch() 则注册了现有的处理程序。这对于用 withCallingHandlers() 而不是 tryCatch() 来处理一个 消息 是最有用的,因为后者会停止程序。
示例
# Using tryCatch()
message_handler <- function(c) cat("Important message is caught!\n")
tryCatch(message = message_handler,
{
message("1st value printed?")
message("Second value too printed!")
})
输出
Important message is caught!
# Using withCallingHandlers()
message_handler <- function(c) cat("Important message is caught!\n")
withCallingHandlers(message = message_handler,
{
message("1st value printed?")
message("Second value too printed!")
})
输出
Important message is caught!
1st value printed?
Important message is caught!
Second value too printed!
自定义信号类
R语言中错误处理的一个挑战是,大多数函数只是用一个字符串调用 stop() 。例如,”预期的 “错误(如模型对某些输入数据集无法收敛)可以被默默忽略,而意外的错误(如没有可用的磁盘空间)可以被传播给用户。
例
# R program to illustrate
# Custom signal classes
condition <- function(subclass, message,
call = sys.call(-1), ...) {
structure(
class = c(subclass, "condition"),
list(message = message, call = call),
...
)
}
is.condition <- function(x) inherits(x, "condition")
e <- condition(c("my_error", "error"),
"Unexpected error occurred")
stop(e) # Output as Unexpected error occurred
# comment out stop(e)
w <- condition(c("my_warning", "warning"),
"Appropriate warning!!!!")
warning(w) # Output as Appropriate warning!!!!
# as well as Important message to be noted!!
# will be printed
m <- condition(c("my_message", "message"),
"Important message to be noted!!!")
message(m) # Output as Important message to be noted!!!
输出
Error: Unexpected error occurred
Execution halted
但同时,如果 stop(e) 行被注释掉,警告和信息都被打印出来 。
Warning message:
Appropriate warning!!!!
Important message to be noted!!
如果warning(w)被注释掉,那么
Important message to be noted!!
所以通过使用自定义信号类,我们可以区分错误。我们可以在下面看到详细的
例子
# R program to illustrate
# Custom signal classes
condition <- function(subclass, message,
call = sys.call(-1), ...) {
structure(
class = c(subclass, "condition"),
list(message = message, call = call),
...
)
}
is.condition <- function(x) inherits(x, "condition")
custom_stop <- function(subclass, message,
call = sys.call(-1),
...) {
c <- condition(c(subclass, "error"), message,
call = call, ...)
stop(c)
}
check_log <- function(x) {
if (!is.numeric(x))
custom_stop("invalid_class",
"check_log() needs numeric input")
if (any(x < 0))
custom_stop("invalid_value",
"check_log() needs positive inputs")
log(x)
}
tryCatch(
check_log("ant"), # As we pass "ant", we will
# get Numeric inputs
# only are allowed as output
# for input, if we give with negative value
# let us check what happens,
# for that uncomment below line and see,
# obviously you get Positive
# numeric value need to be provided
#check_log("-100"),
invalid_class = function(c) "Numeric inputs
only are allowed",
invalid_value = function(c) "Positive numeric value
need to be provided"
)
输出
[1] "Numeric inputs only are allowed"
但与此同时,当我们通过check_log(“100”) 。
[1] "Only positive values are allowed"
极客教程