R error - subscript out of bounds

2019-07-22 06:40发布

问题:

I am trying to run this code which takes a list of addresses and runs each one through Google's Geocode API (using function Addr2latlng below) to get the latitude/longitude and puts each one into a data frame using ProcessAddrList below.

The problem is Addr2latlng works fine for one address and ProcessAddrList works fine for up to 10 addresses, but from 11 addresses or more I get the error below. For 10 addresses this works fine.

To run the code below requires the packages RCurl and RJSONIO to be loaded.

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))

}

回答1:

You are looking to geocode a location using Google Maps. You should use Use geocde from ggmap package.

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

For example:

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:

The original question is a rate limit problem with the Google API. This code fragment, "apiResult <- getURL(url)" is not returning a useable piece of data, so the later try() calls are failing. The previous suggestion of using the ggmap package is a good one. The other possibility is that there are a variety of other geocoding APIs out there that do not have the same limits as Google. Try looking here for starters: http://tinyurl.com/freegeocode