I have a function in R that calls other functions. Occasionally, those functions can return the same message. I only want the message to print once. What is the best way to handle that?
In the example below, functionC will print "The value is 5." two times if the argument for b and c is 5. I only want it to print once.
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)
You can use
withCallingHandlersto catch (and suppress) the messages in real time, then useuniqueto reduce them, then re-messagethem out. I'll add a(n times)when repeated for the sake of transparency (since otherwise you may have no clear idea how noisy inner-calls are).You can repeat the
message=/"muffleMessage"withwarning=/"muffleWarning"to catch warnings as well ... though you might as well usepurrr::quietlyfor that: