我有以下代码:
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
答案 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