gpt4 book ai didi

r - 地理编码地址到 R 中的县

转载 作者:行者123 更新时间:2023-12-05 04:51:27 24 4
gpt4 key购买 nike

我有一个街道地址列表,我想将其地理编码到县。我在 R 中工作。简化示例如下。不幸的是,由于新的 Google API 服务条款,您需要拥有自己的 API key 才能运行我的代码——它不应被共享,因此请不要将其包含在您的解决方案代码中。

我怀疑这是格式问题,但我对 R 太陌生,不知道解决方案。

library(tidyverse)
library(ggmap)

register_google(key = <YOUR GOOGLE KEY>)

ltr <- letters %>% head(5)
adr <- c('110 State St, Albany, NY' ,
'100 State Cir, Annapolis, MD' ,
'206 Washington St SW, Atlanta, GA' ,
'210 State St, Augusta, ME' ,
'1100 Congress Ave, Austin, TX')

rawAdr <- data.frame(ltr , adr)

# the following only retrieves latitude and longitude
latlonAdr <- geocode(location = rawAdr$adr) %>%
bind_cols(rawAdr , .)

# the following retrieves county (among much other information),
# but it is formatted in a way that is
# impossible to use. For instance, county a is in variable long_name...17,
# but the same name is repeated for all addresses. The county for address b is given in
# long_name...64, again the same name for all addresses.

geoAdr <- geocode(location = rawAdr$adr , output = 'all') %>%
bind_cols(rawAdr , . )

我想要一个列出 ltr、adr 和(正确的)县的文件。感谢您的任何帮助! (抱歉,我将在几个小时内无法查看答案。)

最佳答案

geocode 函数的返回值是一个很长的嵌套列表,您需要遍历该列表以找到感兴趣的字段。

这是一个绕过 ggmap 包并返回 JSON 响应的解决方案,这更容易解析:

library(magrittr)

ltr <- letters %>% head(5)
adr <- c('110 State St, Albany, NY' ,
'100 State Cir, Annapolis, MD' ,
'206 Washington St SW, Atlanta, GA' ,
'210 State St, Augusta, ME' ,
'1100 Congress Ave, Austin, TX')
rawAdr <- data.frame(ltr , adr)

#replace spaces with + for a valid web address
adrs <-gsub(" ", "+", adr)
#add the key here to the http address
urls <-paste("https://maps.googleapis.com/maps/api/geocode/json?","address=",adrs,"&key=***keyGoesHere***",sep="")

#query the API, and search for the row that contains the word County and return that value
counties <- sapply(urls, function(url) {
print(url)
rgc <- jsonlite::fromJSON(url)
county <-rgc$results$address_components[[1]]$long_name[grep("County", rgc$results$address_components[[1]]$long_name)]
county
})
rawAdr$County <- counties
rawAdr

关于r - 地理编码地址到 R 中的县,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66913879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com