testthat: handling both warning and value - r

What's the best way to handle calls that generate a warning but then also return a value?
e.g.
> require(testthat)
> expect_warning(log(-1))
> expect_equal(log(-1), NaN)
Warning message:
In log(-1) : NaNs produced
I want to write the test such that the call to log(-1) should both (a) generate a warning and (b) return the value NaN. The way above works, but seeing the "Warning message:" at the bottom might confuse people. Should I suppress warnings temporarily?

require(testthat)
expect_warning(val <- log(-1))
expect_true(is.nan(val))

Related

Warning message within R function seems to make the function not work?

Using the syuzhet package in R, the following works but returns a warning message:
object <- get_text_as_string("path/name.txt")
When I put this in a function, it returns the same warning error but does NOT change the value of object:
gen <- function(file){
object <- get_text_as_string(file)
}
gen("path/name.txt")
This is the warning message, if it matters:
Warning message:
In readLines(path_to_file) :
incomplete final line found on 'path/name.txt'
...but again, I get that from get_text_as_string() when used outside of the function, but it DOES change the value of object.
Anyone have any advice? There must be something I don't understand about functions?
(I've looked for similar questions/answers, if I've missed the right one I'd be happy to just be directed there.)

How to solve- Error: (converted from warning)

I have been getting this error for the first time for commands that used to run well before:
# conversion from char to numeric:
as.numeric(df$col) -> df$col
Error: (converted from warning) NAs introduced by coercion
# running metafor
rma(yi, vi, data=r1s2)
Error: (converted from warning) Studies with NAs omitted from model fitting.
The issue must be with the R environment as these commands are running perfectly on a different computer. The only wrong I can think of is installing a package from GitHub or updating R a few hours ago. The only relevant answer I've found so far is also not working:
Sys.setenv(R_REMOTES_NO_ERRORS_FROM_WARNINGS="true")
This seems to be a warning level issue. If the warning level is 2, warnings become errors. From the documentation, my emphasis.
warn:
integer value to set the handling of warning messages. If warn is negative all warnings are ignored. If warn is zero (the default) warnings are stored until the top–level function returns. If 10 or fewer warnings were signalled they will be printed otherwise a message saying how many were signalled. An object called last.warning is created and can be printed through the function warnings. If warn is one, warnings are printed as they occur. If warn is two (or larger, coercible to integer), all warnings are turned into errors.
old_ops <- options(warn = 2)
warning("this is a warning")
#> Error in eval(expr, envir, enclos): (converted from warning) this is a warning
x <- "a"
as.numeric(x)
#> Error in eval(expr, envir, enclos): (converted from warning) NAs introduced by coercion
options(old_ops)
Created on 2022-06-25 by the reprex package (v2.0.1)
If you say that
The issue must be with the R environment as these commands are running perfectly on a different computer.
then check if you have a file named .RData in your R startup directory. If you have one, then you probably set the warning level in a previous session and now it is being restored every time you run R. Delete this file and this behavior will go away.
See also this SO post.

Additionnal warning message returns an error instead of a warning

I have two functions, f_ that throws an error and f that throws a warning before calling f_.
f_ <- function() stop()
f <- function() {
warning()
f_()
}
Since I have a warning before the error, R produces "additionnal warning messages", but the message in this warning is not my f warning but the error produced in f_ called a 2nd time :
> f()
Error in f_() :
In addition: Warning message:
In f() :
Error in f_() :
It seems to works as expected if the error is produced in the same function or by a built_in function.
f <- function() {
warning()
stop()
}
> f()
Error in f() :
In addition: Warning message:
In f() :
Can someone helps me to understand what is happening there ?
Thanks for any help.
I'm running R version 3.3.2 on x86_64-w64-mingw32 using RStudio.
I think this is caused by the Rstudio error inspector. When encountering an error Rstudio displays the possibility for traceback and debugging. I believe that is the source of the confusion (my own included). The "second" error is simply a feature in Rstudio which assists in debugging as seen below. Note the two buttons on the right allowing you to "show traceback" and "rerun with debug".
In Rstudio
As you can see below, if you run R in a terminal,
this "additional" error is not there.
In a terminal
In your global options in Rstudio, under General tab, you can turn off the use of the debug error handler. You can also do this under Debug -> On Error.
Rstudio will then not display the "additional" message.
Edit:
Upon investigating a bit further, there is something odd going on though. Below, I tried to make the error and warning message a bit more informative with the following observations:
Calling f() many times in a row, it is not entirely clear to me when the error inspector appears and when it does not.
When the error inspector does appear, the warning message is not displayed. When the error inspector does not appear, the warning message is displayed.
I do not know anything about Rstudio's internals, but it is quite definitely the error inspector causing these minor issues.

Create warning log file when running R script

I'd like to create warning/error log for the R script.
Please see below example:
setwd(tempdir())
zz <- file("all.Rout", open="wt")
sink(zz, type="message")
for (i in 1:30){
log(i-50)
}
sink(type="message")
close(zz)
I was expecting that it will enlist all warnings:
Warning messages:
1: In log(i - 50) : NaNs produced
2: In log(i - 50) : NaNs produced
3: In log(i - 50) : NaNs produced
However for the loop i in 1:30 there is only one line in the all.rout file:
There were 30 warnings (use warnings() to see them)
Any idea how to fix it?
I have created the code based on another topic:
Output error/warning log (txt file) when running R script under command line
Try options(warn=1)
From ?options:
'warn': sets the handling of warning messages. If 'warn' is
negative all warnings are ignored. If 'warn' is zero (the
default) warnings are stored until the top-level function
returns. If 10 or fewer warnings were signalled they will be
printed otherwise a message saying how many were signalled.
An object called 'last.warning' is created and can be printed
through the function 'warnings'. If 'warn' is one, warnings
are printed as they occur. If 'warn' is two or larger all
warnings are turned into errors.

Suppress warning message in R console of shiny

We developed a shiny application. It was showing some warning messages, we never bothered it, because the application is working fine. But, we can't distribute the application with warning message appearing in the console. Now my question is, how to suppress the warning message in R console, when shiny application is running.
Insert this in your ui script.
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
)
You actually have two suppress functions via R that work differently for you:
suppressMessages() evaluates its expression in a context that ignores all ‘simple’ diagnostic messages." See ?suppressMessages.
suppressWarnings() evaluates its expression in a context that ignores all warnings. See ?suppressWarnings.
Examples:
f <- function(a) { a ; warning("This is a warning") ; message("This is a message not a warning")}
> f(1)
This is a message not a warning
Warning message:
In f(1) : This is a warning
> suppressWarnings(f(1))
This is a message not a warning
> suppressMessages(f(1))
Warning message:
In f(1) : This is a warning
Wrapping suppressWarnings around your code should work. See ?suppressWarnings. You need to do something like:
atest <- function(n) {warning("a warning"); return(n+1)}
atest(1)
#[1] 2
#Warning message:
#In atest(2) : a warning
suppressWarnings(atest(1))
#[1] 2
But I guess that the better solution is to actually deal with the warning and not just ignore it.

Resources