gpt4 book ai didi

r - 如何在出现警告消息时打印警告消息

转载 作者:行者123 更新时间:2023-12-04 12:28:59 27 4
gpt4 key购买 nike

我有以下代码:

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

最佳答案

调用 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

关于r - 如何在出现警告消息时打印警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com