この質問からは、あなたが Google から何を得ようとしているのか正確にはわかりません。緯度と経度だと思います。そうである場合は、スクリーンショットに続くコードのようなものを試してください。編集: Ari B. Friedman のコメントに従って、パッケージのgeocode
関数を使用した代替 (およびより単純な) アプローチを含めるように改訂されました。ggmap
# Read in the text from your example
mydf <- read.csv(con <- textConnection(
"streetnumber|street|city|state
1150|FM 1960 West Road|Houston|TX
701|Keller Parkway|Keller|TX"), header = TRUE, sep = "|", check.names = FALSE)
# APPROACH 1 - works but Approach 2 probably better (see below)
# Create a new column for the URL to pass to Google API
mydf$url <- with(mydf, paste("http://maps.googleapis.com/maps/api/geocode/xml?address=",
streetnumber,
gsub(" ", "+", street),
city, "+",
state, "+",
"&sensor=false",
sep = ""))
# Check to see what we have in the data frame
str(mydf)
library(XML)
latlon <- lapply(mydf$url, function(x) { # process each element in the column 'url'
myxml <- xmlTreeParse(x, useInternal = TRUE) # pass the element (an URL) to the XML function
# parse the result
lat = xpathApply(myxml, '/GeocodeResponse/result/geometry/location/lat', xmlValue)[[1]]
lon = xpathApply(myxml, '/GeocodeResponse/result/geometry/location/lng', xmlValue)[[1]]
data.frame(lat = lat, lon = lon) # return the latitude and longitude as a data frame
})
# We end up with a list of data frames, so merge the data frames into one:
library(reshape)
latlon <- merge_all(latlon)
# Then bolt the columns on to your existing data frame
mydf <- cbind(mydf, latlon, stringsAsFactors = FALSE)
# We want the latitude and longitude to numbers, not characters
mydf$lat <- as.numeric(mydf$lat)
mydf$lon <- as.numeric(mydf$lon)
require(ggmap)
# APPROACH 2 - let ggmap do the heavy lifting (and
# comment out Approach 1 if you use this)
mydf$location <- with(mydf, paste(streetnumber,street, city, state,sep = ", "))
latlon <- geocode(mydf$location)
mydf <- cbind(mydf, latlon, stringsAsFactors = FALSE)
# Now plot.
# Be careful when specifying the zoom argument, because larger values can cause
# points to be dropped by geom_point()
ggmap(get_googlemap(maptype = 'roadmap', zoom = 6, scale = 2), extent = 'panel') +
geom_point(data = mydf, aes(x = lon, y = lat), fill = "red", colour = "black",
size = 3, shape = 21)