SORU
30 AĞUSTOS 2012, PERŞEMBE


Nasıl R trycatch yazmak

Web indirirken hata ile başa çıkmak için trycatch kod yazmak istiyorum.

url <- c(
    "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
    "http://en.wikipedia.org/wiki/Xz")
y <- mapply(readLines, con=url)

Bu iki ifade başarıyla tamamlandı. Aşağıda olmayan, mevcut bir web adresi oluşturmak:

url <- c("xxxxx", "http://en.wikipedia.org/wiki/Xz")

url[1] yok. Nasıl ki: trycatch bir döngü (fonksiyon) yazmak yok

  1. Url yanlış çıktı: "web url yanlış olamaz".
  2. Url yanlış olduğunda, kod durdurmaz, ama URL listenin sonuna kadar indirmek için devam ediyor?

CEVAP
30 AĞUSTOS 2012, PERŞEMBE


İyi o zaman: R dünya için; - hoş geldiniz)

Al bakalım

Kodu ayarlama

urls <- c(
    "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
    "http://en.wikipedia.org/wiki/Xz",
    "xxxxx"
)
readUrl <- function(url) {
    out <- tryCatch(
        {
            # Just to highlight: if you want to use more than one 
            # R expression in the "try" part then you'll have to 
            # use curly brackets.
            # 'tryCatch()' will return the last evaluated expression 
            # in case the "try" part was completed successfully

            message("This is the 'try' part")

            readLines(con=url, warn=FALSE) 
            # The return value of `readLines()` is the actual value 
            # that will be returned in case there is no condition 
            # (e.g. warning or error). 
            # You don't need to state the return value via `return()` as code 
            # in the "try" part is not wrapped insided a function (unlike that
            # for the condition handlers for warnings and error below)
        },
        error=function(cond) {
            message(paste("URL does not seem to exist:", url))
            message("Here's the original error message:")
            message(cond)
            # Choose a return value in case of error
            return(NA)
        },
        warning=function(cond) {
            message(paste("URL caused a warning:", url))
            message("Here's the original warning message:")
            message(cond)
            # Choose a return value in case of warning
            return(NULL)
        },
        finally={
        # NOTE:
        # Here goes everything that should be executed at the end,
        # regardless of success or error.
        # If you want more than one expression to be executed, then you 
        # need to wrap them in curly brackets ({...}); otherwise you could
        # just have written 'finally=<expression>' 
            message(paste("Processed URL:", url))
            message("Some other message at the end")
        }
    )    
    return(out)
}

Kod uygulanması

> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory

Çıkış araştırıyor

> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"      
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"      
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"             
[5] "</head><body>"                                                          
[6] ""    

> length(y)
[1] 3

> y[[3]]
[1] NA

Ek açıklamalar

tryCatch

tryCatch bir hata veya bir uyarı olmadığı sürece expr yürütme için ilişkilendirilmiş değeri döndürür. Bu durumda, belirli bir dönüş değeri (return(NA) yukarıya bakın) ilgili bir işleyici işlevi (bağımsız değişken error ve ?tryCatch 19*) sağlayarak belirtilebilir. Bu zaten var olan fonksiyonlar olabilir, ama aynı zamanda tryCatch() yukarıda yaptığım gibi) içerisinde tanımlayabilirsiniz.

Belirli bir dönüş seçme sonuçları işleyicisi işlevleri değerleri

NA hata durumunda iade edilmesi gerektiğini belirttiği gibi, y üçüncü öğe NA. Eğer birlikte olursak, seçilmiş NULL için dönüş değeri, uzunluğu y tıpkı si 2 yerine 3 lapply() sadece "Yoksay" dönüş değerleri NULL. Ayrıca eğer bir belirtin yok eğer unutmayınaçıkNULL döner return()) değer (bir hata veya uyarı durumu yani) dönüş.

"İstenmeyen" uyarı mesajı

warn=FALSE herhangi bir etkisi var gibi görünmüyor, Uyarı Bu durumda gerçekten ilgi çekici değil () bastırmak için alternatif bir yol kullanmaktır

suppressWarnings(readLines(con=url))

yerine

readLines(con=url, warn=FALSE)

Birden çok ifadeler

Unutmayın, ya da her yerde birden fazla ifadelerde "gerçek ifadeler parçası" (bağımsız değişken expr tryCatch()) sarma onlara süslü parantez (sadece hoşuma resimli finally kısmı).

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • BumbleDroid

    BumbleDroid

    18 EKİM 2010
  • Lupe Fiasco

    Lupe Fiasco

    23 ŞUBAT 2006
  • Maschine Tutorials

    Maschine Tut

    15 ŞUBAT 2011