【问题标题】:R error - subscript out of boundsR错误 - 下标超出范围
【发布时间】:2013-12-01 23:26:16
【问题描述】:

我正在尝试运行此代码,该代码获取地址列表并通过 Google 的 Geocode API(使用下面的函数 Addr2latlng)运行每个地址以获取纬度/经度,并使用下面的 ProcessAddrList 将每个地址放入数据框中。

问题是 Addr2latlng 适用于一个地址,而 ProcessAddrList 适用于最多 10 个地址,但从 11 个或更多地址中我得到以下错误。对于 10 个地址,这可以正常工作。

要运行下面的代码,需要加载包 RCurl 和 RJSONIO。

Error in geoStruct$results[[1]] : subscript out of bounds
Error in geoStruct$results[[1]] : subscript out of bounds


ProcessAddrList <- function(addrList)

{
  resultDF <- data.frame(atext=character(),X=numeric(),Y=numeric(),EID=numeric())

  i <- 1

  for (addr in addrList)

  {
    latlng = Addr2latlng(addr)
    resultDF <-rbind(resultDF,data.frame(atext=addr,X=latlng[[2]],Y=latlng[[1]],EID=i))
    i <- i+1
  }

  return (resultDF)
}

Addr2latlng <- function(address)

{
  url <- MakeGeoURL(address)
  apiResult <- getURL(url)
  geoStruct <- fromJSON(apiResult, simplify = FALSE)
  lat <- NA
  lng <- NA
  try(lat <- geoStruct$results[[1]]$geometry$location$lat)
  try(lng <- geoStruct$results[[1]]$geometry$location$lng)
  return(c(lat, lng))

}

【问题讨论】:

  • 您确定没有达到 Google API 的速率限制吗?

标签: r google-geocoding-api rcurl rjsonio


【解决方案1】:

您希望使用 Google 地图对位置进行地理编码。 您应该使用来自ggmap 包的geocde

library(ggmap) 
sapply(addrList,geocode) ##google maps api limits to 2500 queries a day.

例如:

library(ggmap)
addrList <- c('Paris','Djerba','London')
sapply(addrList,geocode) 

#      Paris    Djerba   London    
# lon 2.352222 10.84515 -0.1198244
# lat 48.85661 33.8076  51.51121 

【讨论】:

    【解决方案2】:

    最初的问题是 Google API 的速率限制问题。此代码片段“apiResult http://tinyurl.com/freegeocode

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多