Create warning log file when running R script - r

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.

Related

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.

R: What causes "In eval(ei, envir) : NAs introduced by coercion"?

I sometimes get the following warning in my R code output:
Warning message:
In eval(ei, envir) : NAs introduced by coercion
This happens only when running my R code with R --slave --file=/path/to/sourcecode.R --args arg1 arg2 arg3 arg4 or Rscript /path/to/sourcecode.R arg1 arg2 arg3 arg4 but not when running the code interactively (not even if I run it in an interactive R session on a cluster node).
I cannot provide example code to reproduce the problem because this is a large project with a lot of code spread across several files, and I'm not sure what specific code or circumstances are triggering it.
Googling the error, I found references to an error message referencing "eval(ei, envir)" that happens when you call source from inside of a function . The message I get is different - the post in the link is an error about not being able to find a variable, mine is a warning about NAs being introduced by coercion. So it's probably not the same problem, but I suspect it is somehow still related to using source(), because my code also uses source().
If I knew what "ei" was and why using source() apparently involves calling eval(ei,envir), that might help me figure out what exactly (an environment variable? which one?) has something in it that would trigger an "NAs introduced by coercion" message... does anyone have any ideas what might be going on here?
I have figured out what was causing this. Since Google searches did not find any exact matches for this message, I'm making a Q&A-style post in hopes it will help the next person to Google this particular error.
The warning happens when a variable or other object created in your main code contains values that get coerced to NA in code that you have loaded via source(). Here is some example code to cause it:
test1.R:
print("Starting test1.R")
x <- c('3','bicycle','5')
source('test2.R')
print('Finished test1.R.')
test2.R:
print("Starting test2.R")
y <- as.numeric(x)
print("Finished test2.R")
The output of Rscript test1.R is:
[1] "Starting test1.R"
[1] "Starting test2.R"
[1] "Finished test2.R"
Warning message:
In eval(ei, envir) : NAs introduced by coercion
[1] "Finished test1.R."
Note that even though the line that triggers the error happens in the middle of the code loaded with source(), you don't see the warning in your output until after the code loaded by source() has finished.
You also don't have to be running in batch mode for it to happen. Here I use source() in interactive mode to cause the same message:
> x <- c('3','bicycle','5')
> source('test2.R')
[1] "Starting test2.R"
[1] "Finished test2.R"
Warning message:
In eval(ei, envir) : NAs introduced by coercion
So why was this only happening in batch mode in my original problem? It turned out to be a red herring... when I ran my code in interactive mode, I created a vector to simulate command-line arguments, like this: args <- c('/path/to/infile','27',NA,'0.1'). But when my code was running in batch mode, it created the vector "args" like this: args <- commandArgs(trailingOnly=T). And an NA passed as a command line argument is not a real NA, it is the string 'NA'. So as.numeric('NA') coerces 'NA' to NA. But the argument was only 'NA' instead of NA when running in batch mode.
Those two quirks combined were enough to cause a troubleshooting nightmare that cost me a whole evening. Hopefully this Q&A-style post will save the next person to Google this error message some time!

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.

testthat: handling both warning and value

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))

Problems creating plot with boxcox using rapache module function

I'm trying to create a plot using boxcox function from package MASS.
but it's creating an rapache error.
The r code:
<%
csvDF<- read.csv(GET$name1, header=TRUE)
a<-lm(csvDF[,GET$col_variable]~1)
require(MASS)
filename1 <- paste(tempfile(tmpdir='/var/www/images'), '.png', sep='')
png(filename1)
bx<-boxcox(a)
dev.off()
%>
**GET$name1 is the csv data file address.
**GET$col_variable is the variables column.
When I lose the "bx<-boxcox(a)" line the error disappear, so I guess that the boxcox causes the error.
Here are the rapache errors:
RApache Warning/Error!!!
Error in eval(expr, envir, enclos) : object 'csvDF' not found
RApache Warning/Error!!!
In addition:
RApache Warning/Error!!!
Warning messages:
RApache Warning/Error!!!
1: In readLines(icon, 1) : incomplete final line found on '/var/www/brew/sampleplan/step5_box_cox.php'
RApache Warning/Error!!!
2: In readLines(icon, 1) : incomplete final line found on '/var/www/brew/sampleplan/step5_box_cox.php'
RApache Warning/Error!!!
3: In readLines(icon, 1) : incomplete final line found on '/var/www/brew/sampleplan/step5_box_cox.php'
RApache Warning/Error!!!
4: In readLines(icon, 1) : incomplete final line found on '/var/www/brew/sampleplan/step5_box_cox.php'
RApache Warning/Error!!!
5: In readLines(icon, 1) : incomplete final line found on '/var/www/brew/sampleplan/step5_box_cox.php'
RApache Warning/Error!!!
Function brew returned an object of 'try-error'. Returning HTTP response code 500.
I will be gratefull for any suggestion.
It is very difficult to give a complete answer because your whole setup isn't available. The error message (as opposed to the warnings; worry about them later) is the variable csvDF isn't found. It is unclear whether this error happens before or after you call read.csv. Either way, the problem isn't the call to boxcox.
Also note that lm has a data argument that could make your code clearer. Try something like
lm_formula <- as.formula(paste(col_variable, "1", sep = "~"))
a <- lm(lm_formula, data = csvDF)
You would also benefit from separating out code that reads data, calculates statistics, creates plots and writes plots to file.

Resources