目的:使用R,獲得緯度和經度的數據地址的矢量通過open.mapquestapi地理編碼一批地址與開放mapquestapi
出發點:由於geocode
從ggmap
包被限制到一天2500個查詢,我需要找到一個不同的方式(我的data.frame由9M條目組成)。數據科學工具包不是一種選擇,因爲我的大部分地址都位於英國/美國以外。我使用open.mapquestapi在http://rpubs.com/jvoorheis/Micro_Group_Rpres上發現了這個優秀片段。
geocode_attempt <- function(address) {
URL2 = paste("http://open.mapquestapi.com/geocoding/v1/address?key=", "Fmjtd%7Cluub2huanl%2C20%3Do5-9uzwdz",
"&location=", address, "&outFormat='json'", "boundingBox=24,-85,50,-125",
sep = "")
# print(URL2)
URL2 <- gsub(" ", "+", URL2)
x = getURL(URL2)
x1 <- fromJSON(x)
if (length(x1$results[[1]]$locations) == 0) {
return(NA)
} else {
return(c(x1$results[[1]]$locations[[1]]$displayLatLng$lat, x1$results[[1]]$locations[[1]]$displayLatLng$lng))
}
}
geocode_attempt("1241 Kincaid St, Eugene,OR")
我們需要這些庫:
library(RCurl)
library(rjson)
library(dplyr)
讓我們創建一個實物模型data.frame 5不會忽略。
id <- c(seq(1:5))
street <- c("Alexanderplatz 10", "Friedrichstr 102", "Hauptstr 42", "Bruesseler Platz 2", "Aachener Str 324")
postcode <- c("10178","10117", "31737", "50672", "50931")
city <- c(rep("Berlin", 2), "Rinteln", rep("Koeln",2))
country <- c(rep("DE", 5))
df <- data.frame(id, street, postcode, city, country
對於添加緯度lat
和經度lon
變量,我們可以用一個for
-loop工作data.frame。我將介紹這些代碼,只是爲了說明該功能在原理上起作用。
for(i in 1:5){
df$lat[i] <- geocode_attempt(paste(df$street[i], df$postcode[i], df$city[i], df$country[i], sep=","))[1]
df$lon[i] <- geocode_attempt(paste(df$street[i], df$postcode[i], df$city[i], df$country[i], sep=","))[2]
}
從性能的角度來看,這段代碼非常糟糕。即使對於這個小的數據框架,我的電腦也花了大約9秒,很可能是因爲web服務查詢,但沒關係。所以我可以在我的9M行上運行這些代碼,但時間會很長。
我的嘗試是利用dplyr
包中的mutate
函數。 這裏是我的嘗試:在只有2.3秒
df %>%
mutate(lat = geocode_attempt(paste(street, postcode, city, country, sep=","))[1],
lon = geocode_attempt(paste(street, postcode, city, country, sep=","))[2])
system.time
停止。不錯。但現在的問題是:
id street postcode city country lat lon
1 1 Alexanderplatz 10 10178 Berlin DE 52.52194 13.41348
2 2 Friedrichstr 102 10117 Berlin DE 52.52194 13.41348
3 3 Hauptstr 42 31737 Rinteln DE 52.52194 13.41348
4 4 Bruesseler Platz 2 50672 Koeln DE 52.52194 13.41348
5 5 Aachener Str 324 50931 Koeln DE 52.52194 13.41348
lat
和lon
正是所有條目的相同。在我的理解中,mutate
函數正在逐行工作。但在這裏,緯度和經度是從第一行算起的。因此,第一行是正確的。有沒有人有一個想法,爲什麼?我提供的代碼是完整的。沒有額外的加載。有任何想法嗎?如果你有一個高性能的替代方法,而不是優化我的代碼,我會很感激。
@NicE提供的查詢如何最終爲您的9M行工作?是你能夠進行地理編碼所有實例的時間相對較少,還是你擊中MapQuest的限制? – bshelt141 2017-05-12 11:57:28