我正在尝试使用 ggmap 库中的 revgeodcode 函数获取经度纬度坐标(长)列表的邮政编码。
我的问题和数据与这里相同:在 FOR 循环中使用 revgeocode 函数。需要帮助,但接受的答案对我不起作用。
我的数据 (.csv):
ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439
我遵循相同的步骤:
data <- read.csv(file.choose())
dset <- as.data.frame(data[,2:3])
location = dset
locaddr <- lapply(seq(nrow(location)), function(i){
revgeocode(location[i,],
output = c("address"),
messaging = FALSE,
sensor = FALSE,
override_limit = FALSE)
})
。并收到错误消息:"错误:is.numeric(location) && length(location) == 2 不是 TRUE"具体来说,is.numeric(location) 是 FALSE,这看起来很奇怪,因为我可以乘以 2 并得到预期的答案。
任何帮助将不胜感激。
这里有很多错误。
首先,纬度和经度颠倒了。数据集中的所有位置(如指定)都位于南极洲。
其次,revgeocode(...)
期望一个长度为 2 的数字向量,按该顺序包含经度和纬度。您正在传递一个data.frame
对象(这是错误的原因),并且根据 (1) 它的顺序错误。
第三,revgeocode(...)
使用谷歌地图API,它限制你每天2500次查询。因此,如果您确实拥有大型数据集,祝您好运。
此代码适用于您的示例:
data <- read.csv(text="ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439")
library(ggmap)
result <- do.call(rbind,
lapply(1:nrow(data),
function(i)revgeocode(as.numeric(data[i,3:2]))))
data <- cbind(data,result)
data
# ID Longitude Latitude result
# 1 311175 41.29844 -72.92918 16 Church Street South, New Haven, CT 06519, USA
# 2 292058 41.93694 -87.66984 1632 West Nelson Street, Chicago, IL 60657, USA
# 3 12979 37.58096 -77.47144 2077-2199 Seddon Way, Richmond, VA 23230, USA
这将提取邮政编码:
library(stringr)
data$zipcode <- substr(str_extract(data$result," [0-9]{5}, .+"),2,6)
data[,-4]
# ID Longitude Latitude zipcode
# 1 311175 41.29844 -72.92918 06519
# 2 292058 41.93694 -87.66984 60657
# 3 12979 37.58096 -77.47144 23230
我已经编写了软件包googleway,以使用有效的API密钥访问Google maps API。因此,如果您的数据大于 2,500 个项目,您可以为 API 密钥付费,然后使用googleway::google_reverse_geocode()
例如
data <- read.csv(text="ID, Longitude, Latitude
311175, 41.298437, -72.929179
292058, 41.936943, -87.669838
12979, 37.580956, -77.471439")
library(googleway)
key <- "your_api_key"
res <- apply(data, 1, function(x){
google_reverse_geocode(location = c(x["Latitude"], x["Longitude"]),
key = key)
})
## Everything contained in 'res' is all the data returnd from Google Maps API
## for example, the geometry section of the first lat/lon coordiantes
res[[1]]$results$geometry
bounds.northeast.lat bounds.northeast.lng bounds.southwest.lat bounds.southwest.lng location.lat location.lng
1 -61.04904 180 -90 -180 -75.25097 -0.071389
location_type viewport.northeast.lat viewport.northeast.lng viewport.southwest.lat viewport.southwest.lng
1 APPROXIMATE -61.04904 180 -90 -180
要提取邮政编码,只需写下:
>data$postal_code