我正在尝试使用ggmap库中的revgeodcode函数获取经度纬度坐标(长)列表的Zip代码。
我的问题&数据与此处相同:Using revgeocode function in a FOR loop. Help required但接受的答案对我不起作用。
我的数据(.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(位置)&amp;&amp; length(location)== 2不为TRUE” 具体来说,is.numeric(location)为FALSE,这看起来很奇怪,因为我可以乘以2得到预期的答案。
任何帮助都将不胜感激。
答案 0 :(得分:11)
这里有很多不妥之处。
首先,你有经纬度逆转。指定的数据集中的所有位置都位于南极洲。
其次,revgeocode(...)
期望长度为2的数字向量包含该顺序的经度和纬度。您正在传递data.frame
对象(这是错误的原因),并且按照(1)它的顺序错误。
第三,revgeocode(...)
使用google maps 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
这会提取zipcode:
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
答案 1 :(得分:2)
我已经使用有效的API密钥编写了包googleway来访问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
答案 2 :(得分:-1)
要提取邮政编码,请写下:
>data$postal_code