Reputation: 322
I would like to calculate the route between multiple addresses using the route function in ggmap. I came up with 2 alternative solutions, but both don't work:
*alternative 1
First I made 2 vectors: one with points of interest (4 in total) and another one with the base address.
points_of_interest <- c(
"berlin",
"paris",
"new york",
"madrid")
base_address <- "helsinki"
The following should calculate the exact route between each pair of points_of_interest and base_address. So a total of 4 routes: berlin - helsinki, paris - helsinki, new york - helsinki and madrid - helsinki.
calculatedroutes1 <- route(from = base_address,
to = points_of_interest)
The problem is I only get the route for berlin-helsinki, although I thought it should be vectorized.
*alternative 2
Since route
didn't seem to vectorize I thought maybe I could use plyr. So this was my alternative code:
df.routes <- data.frame(points_of_interest,
rep(base_address, each = length(points_of_interest),
stringsAsFactors = FALSE)
df. calculatedroutes2 <- ddply(.data = df.routes,
.variables = .(points_of_interest, base_address),
.fun = route,
points_of_interest,
base_address)
For each combination of points_of_interest and base_address (so for all 4 routes) I wanted to use the function route
with arguments from = points_of_interest
and to = base_address
. This generated the error Error: unexpected ',' in "points_of_interest,
but I think this is the right way to add arguments to a function in ddply?
Another question which is similar to mine other error route function is still unanswered.
Upvotes: 2
Views: 1181
Reputation: 11
This generated the error Error: unexpected ',' in "points_of_interest, but I think this is the right way to add arguments to a function in ddply?
I guess you should put those arguments between quotes:
df. calculatedroutes2 <- ddply(.data = df.routes,
.variables = .(points_of_interest, base_address),
.fun = route,
"points_of_interest",
"base_address")
Upvotes: 1
Reputation: 59345
Looking at the code for route(...)
(just type "route" at the command line, no ?
or ()
), this function is not vectorized, although the documentation suggests it is.
route(...)
uses the Google Directions API, which takes a single origin and a single destination. If you pass a vector in the to=...
argument, route(...)
creates a vector of urls, but only uses the first one.
One way around this uses the Vectorize(...)
function in R:
rt <- Vectorize(route,vectorize.args=c("from","to"),SIMPLIFY=FALSE)
rt(base_address,points_of_interest)
This, too will fail with your definitions for points_of_interest
, because Google Directions supports three mode of transport: driving, bicycle, and walk, and none of these will get you from Helsinki to NY. If you remove new york
from points of interest, you get a list of data frames with the routes from Helsinki to each of the other cities.
Upvotes: 2