Adam Adam - 1 year ago 123
R Question

Displaying warnings generate by R script as they happen

I have a script that contains multiplte blocks with lines that look like this...

#Read data for X
DataX = read.delim(file = 'XRecords.txt',
col.names = XFields[,'FieldName'])
print('Data X read')
#Convert fields that should be numeric into numeric so they can summed
DataX[,NumFieldNames] = as.numeric(as.character(XData[,NumFieldNames]))
print('Data X scrubbed')

When I source the script I get an output like this...

[1] "Data X read"
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"
Warning message:
In eval(expr, envir, enclos) : NAs introduced by coercion

Based on that output, I reload data Y and began looking for records where the string to numeric conversion failed. After a couple hours of frustration, I realized that data X was actually the one that had type conversion errors.

It looks like what's happening is that an error is raised, but it does not display on the console until the script finishes. Is there a way to make errors output to the console as soon as they are raised? I tried flush.console(), but it doesn't seem to work for warnings.

I'd prefer not to have load any additional packages onto my system if it can be avoided. I'm using this for work, and I had to jump through a few hoops just to get the CRAN distribution installed on my computer.

Thank you. I appreciate the help.

In case it's relevant:

  • version.string R version 2.15.2 (2012-10-26)

  • Running via RStudio v0.97.318

  • Windows 7

Answer Source

Let's make an example that shows the problem

foo <- function() {
  X <- c("1", "2", "three")
  print("Data X read")
  X <- as.numeric(X)
  print("Data X scrubbed")
  Y <- c("1", "2", "3")
  print("Data Y read")
  Y <- as.numeric(Y)
  print("Data Y scrubbed")

If run (even interactively), the behavior you see appears

> foo()
[1] "Data X read"
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"
Warning message:
In foo() : NAs introduced by coercion

Behavior of warnings is handled with the warn option (see help("options")). That gives the choices including

If warn is one, warnings are printed as they occur.

Changing the option to 1 then gives

> options(warn=1)
> foo()
[1] "Data X read"
Warning in foo() : NAs introduced by coercion
[1] "Data X scrubbed"
[1] "Data Y read"
[1] "Data Y scrubbed"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download