【问题标题】:Keep R code running despite Errors?尽管出现错误,但仍保持 R 代码运行?
【发布时间】:2014-08-21 04:57:12
【问题描述】:

使用上一个 stackoverflow 中的这个代码函数:R: How to GeoCode a simple address using Data Science Toolbox

require("RDSTK")
library(httr)
library(rjson)

geo.dsk <- function(addr){ # single address geocode with data sciences toolkit
 require(httr)
 require(rjson)
  url      <- "http://www.datasciencetoolkit.org/maps/api/geocode/json"
 response <- GET(url,query=list(sensor="FALSE",address=addr))
json <- fromJSON(content(response,type="text"))
loc  <- json['results'][[1]][[1]]$geometry$location
return(c(address=addr,long=loc$lng, lat= loc$lat))
}

现在示例代码。这工作正常:

City<-c("Atlanta, USA", "Baltimore, USA", "Beijing, China")
r<- do.call(rbind,lapply(as.character(City),geo.dsk))

这不起作用。它说:“json ["results"][[1]][[1]] 中的错误:下标越界”

 Citzy<-c("Leicester, United Kingdom")
 do.call(rbind,lapply(as.character(Citzy),geo.dsk))

我认为错误是因为它找不到城市。所以我希望代码忽略它并继续运行。我该怎么做呢?任何帮助将不胜感激!

【问题讨论】:

    标签: warnings subscript


    【解决方案1】:

    最好使用 try/catch 块来处理错误。在 R 中,这看起来像这样 (source):

    result = tryCatch({
        # write your intended code here
        Citzy<-c("Leicester, United Kingdom")
        do.call(rbind,lapply(as.character(Citzy),geo.dsk))
    }, warning = function(w) {
        # log the warning or take other action here
    }, error = function(e) {
        # log the error or take other action here
    }, finally = {
        # this will execute no matter what else happened
    })
    

    因此,如果您遇到错误,它将进入错误块(并跳过“尝试”部分中的其余代码),而不是停止您的程序。请注意,您应该始终对错误“做点什么”,而不是完全忽略它;将消息记录到控制台和/或设置错误标志是一件好事。

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2016-04-05
      相关资源
      最近更新 更多