for loop through google geocode() 但跳过相同的县以减少 google API 查询

for loop trough google geocode() but skip identical counties to reduce google API enquiries

谁能帮我在这个 for 循环中实现一个 if 语句来跳过相同的国家/地区名称。 IE。西班牙在示例中重复了几次,但只需要询问 API 一次,因为 google API 服务有限制。但是,我想每次都粘贴西班牙或其他重复名称的经纬度。

不幸的是,您需要自己的密钥,否则代码不会 运行。

register_google(key='your key')
t<-data.frame(importer_country=c("spain", "spain", "spain","united states","spain","eswatini", "spain", "spain", "spain", "spain", "spain", "spain", "spain"))
t$importer_country<-as.character(t$importer_country)
for(i in 1:nrow(t)){
  result <- geocode(t$importer_country[i], output = "latlon", source = "google")
  t$importer_lon[i] <- as.numeric(result[1])
  t$importer_lat[i] <- as.numeric(result[2])
}
head(t)

一个直接的解决方案是创建一个具有唯一名称集的新数据框。拉取请求的数据,然后将缩减数据帧的数据与原始数据集合并。

#Create a subset dataframe with unique country names
library(tibble)  #improved data frames
reducedt <- tibble(importer_country = t[!duplicated(t$importer_country), ])

#run function as is with reduced subset
for(i in 1:nrow(reducedt)){
  result <- geocode(reducedt$importer_country[i], output = "latlon", source = "google")
  reducedt$importer_lon[i] <- as.numeric(result[1])
  reducedt$importer_lat[i] <- as.numeric(result[2])
}

#join the two data frames together.
library(dplyr)
finalnanswer <- left_join(t, reducedt)

另请注意,geocode 函数很可能是矢量化的,因此您可能不需要循环。

编辑
向量化 geocode() 函数。使用最新版本"ggmap" version >= 3.0.0.901(早期版本geocode函数有bug)

reducedt <- tibble(importer_country = t[!duplicated(t$importer_country), ])

result <- geocode(reducedt$importer_country, output = "latlon", source = "google")
reducedt<-cbind(reducedt, result)

finalnanswer <- left_join(t, reducedt)