簡體   English   中英

R錯誤-下標超出范圍

[英]R error - subscript out of bounds

我正在嘗試運行此代碼,該代碼采用地址列表,並通過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 Maps對位置進行地理編碼。 您應該使用ggmap包中的Use 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 

最初的問題是Google API的速率限制問題。 此代碼段“ apiResult <-getURL(url)”未返回可用數據,因此以后的try()調用失敗。 先前使用ggmap軟件包的建議是一個很好的建議。 另一種可能性是,還有許多其他地理編碼API的限制與Google不同。 嘗試在這里尋找入門者: http : //tinyurl.com/freegeocode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM