我在 R 中有一个函数可以调用其他函数。有时,这些函数可以返回相同的消息。我只想将消息打印一次。处理这个问题的最佳方法是什么?
在下面的示例中,
functionC
将打印“The value is 5”。如果 b 和 c 的参数为 5,则打印两次。我只想打印一次。
functionA <- function(a){
if(a==5){
message("The value is 5.")
}
return(a-2)
}
functionB <- function(b){
if(b==5){
message("The value is 5.")
}
return(b+7)
}
functionC <- function(a,b){
a <- functionA(a)
b <- functionB(b)
c <- rbind(a,b)
return(c)
}
functionC(5,5)
您可以使用
withCallingHandlers
实时捕获(并抑制)消息,然后使用 unique
减少消息,然后重新 message
将它们删除。为了透明起见,我会在重复时添加 (n times)
(否则您可能不清楚该消息是从哪个内部调用发出的)。
functionC <- function(a,b){
msgs <- character(0)
a <- withCallingHandlers(
functionA(a),
message = function(m) {
msgs <<- c(msgs, conditionMessage(m))
invokeRestart("muffleMessage")
})
b <- withCallingHandlers(
functionB(b),
message = function(m) {
msgs <<- c(msgs, conditionMessage(m))
invokeRestart("muffleMessage")
})
msgs <- trimws(msgs)
# since 'table' does not preserve the original order, we'll do a few
# extra steps to ensure the messages appear in the order of their
# _first_ appearance
counts <- table(msgs)
counts <- counts[match(names(counts), msgs)]
msgs <- paste0(names(counts), ifelse(counts > 1, sprintf(" (%d times)", counts), ""))
for (m in msgs) message(m)
c <- rbind(a, b)
return(c)
}
functionC(5,5)
# The value is 5. (2 times)
# [,1]
# a 3
# b 12
抑制 functionA/functionB 警告并包含新的“a 和/或 b is 5”警告是否适合您的用例?例如
functionA <- function(a){
if(a==5){
message("The value is 5.")
}
return(a-2)
}
functionB <- function(b){
if(b==5){
message("The value is 5.")
}
return(b+7)
}
functionC <- function(a,b){
a <- functionA(a)
b <- functionB(b)
c <- rbind(a,b)
return(c)
}
functionC(5,5)
#> The value is 5.
#> The value is 5.
#> [,1]
#> a 3
#> b 12
functionD <- function(a,b){
if(a==5 | b==5){
message("The value of a and/or b is 5.")
}
a <- suppressMessages(functionA(a))
b <- suppressMessages(functionB(b))
c <- rbind(a,b)
return(c)
}
functionD(5,5)
#> The value of a and/or b is 5.
#> [,1]
#> a 3
#> b 12
创建于 2023-08-18,使用 reprex v2.0.2