2012-08-31 42 views
3

警告消息,我有以下代碼:如何打印,因爲它們發生

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 

回答

9

致電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 
+0

親愛andrie,我知道suppressWarnings功能,當你不使用它,爲什麼警告message'In文件(CON, 「R」):無法打開文件'xxxxx':輸出結束時沒有這樣的文件或目錄?可能包裝消息將在第四行,而不是結尾? –

+0

@DdPp我用第二個選項編輯了我的答案。 – Andrie