如何在出现警告消息时打印它们

时间:2012-08-31 08:37:38

标签: r warnings

我有以下代码:

urls <- c(
    "xxxxx",
    "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
    "http://en.wikipedia.org/wiki/Xz"        
)
readUrl <- function(url) {
out <- tryCatch(
    readLines(con=url, warn=FALSE),
    error=function(e) {
        message(paste("URL does not seem to exist:", url))
        message(e)
        return(NA)
    },
    finally=message(paste("Processed URL:", url))
)    
return(out)
}
y <- lapply(urls, readUrl)

当我运行它时,我得到:

URL does not seem to exist: xxxxx  
cannot open the connectionProcessed URL: xxxxx    
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html  
Processed URL: http://en.wikipedia.org/wiki/Xz  
Warning message:  
In file(con, "r") : cannot open file 'xxxxx': No such file or directory  

但我期待:

URL does not seem to exist: xxxxx   
cannot open the connectionProcessed URL: xxxxx    
Warning message:    
In file(con, "r") : cannot open file 'xxxxx': No such file or directory  
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html  
Processed URL: http://en.wikipedia.org/wiki/Xz  

那么,为什么我会得到:

Warning message:    
In file(con, "r") : cannot open file 'xxxxx': No such file or directory   

1 个答案:

答案 0 :(得分:10)

readLines的调用会发出警告。您可以使用suppressWarnings()取消警告。试试这个:

readUrl <- function(url) {
  out <- tryCatch(
    suppressWarnings(readLines(con=url, warn=FALSE)),
    error=function(e) {
      message(paste("URL does not seem to exist:", url))
      message(e)
      return(NA)
    },
    finally=message(paste("Processed URL:", url))
  )    
  return(out)
}
y <- lapply(urls, readUrl)

屏幕输出:

URL does not seem to exist: xxxxx
cannot open the connectionProcessed URL: xxxxx
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Processed URL: http://en.wikipedia.org/wiki/Xz

或者,您可以使用options(warn=1)在出现警告时显示警告。试试这个:

readUrl <- function(url) {
  op <- options("warn")
  on.exit(options(op))
  options(warn=1)
  out <- tryCatch(
    readLines(con=url, warn=FALSE),
    error=function(e) {
      message(paste("URL does not seem to exist:", url))
      message(e)
      return(NA)
    },
    finally=message(paste("Processed URL:", url))
  )    
  return(out)
}
y <- lapply(urls, readUrl)

输出:

Warning in file(con, "r") :
  cannot open file 'xxxxx': No such file or directory
URL does not seem to exist: xxxxx
cannot open the connectionProcessed URL: xxxxx
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Processed URL: http://en.wikipedia.org/wiki/Xz