I've been looking for how to interact with an API error inside R functions without success. I found solutions with tryCatch()
but I'm not realizing it, so I decided to ask here.
I have a dataset like this below.
fluxo <-
structure(list(code_o = c("355030802000004", "355030802000012", "355030802000013",
"355030802000014", "355030802000030", "355030802000036"),
code_d = c("3503488", "3503488", "3503488", "3503488", "3503488", "3503488"),
fx = c(-46.70104009, -46.69845387, -46.69815333,
-46.70141047, -46.69755981, -46.69996442),
fy = c(-23.55023455, -23.54720393, -23.55123612,
-23.55210794, -23.54364215, -23.55333346),
tx = c(-46.7224721383401, -46.7224721383401, -46.7224721383401,
-46.7224721383401, -46.7224721383401, -46.7224721383401),
ty = c(-23.5375321244996, -23.5375321244996, -23.5375321244996,
-23.5375321244996, -23.5375321244996, -23.5375321244996)),
.Names = c("code_o", "code_d", "fx", "fy", "tx", "ty"),
row.names = c(NA, 6L), class = "data.frame")
To find distances and travel durations between code_o and code_d points I'm using dist_google()
function from stplanr
package, which interacts with Google Distance Matrix API. The function get just all-to-all results (all code_o to all code_d) and I want just the given row pairs. Because this I wrote the for looping below to make this task.
library(stplanr)
tempos_falta_ubs <- data.frame()
for (linha in 1:nrow(fluxo)) {
origin <- fluxo[linha, 3:4]
destiny <- fluxo[linha, 5:6]
tempos_falta_ubs <- rbind(tempos_falta_ubs,
dist_google(from=origin,
to=destiny,
mode='walking'))
}
But some times it returns this error message:
Error: No results for this request (e.g. due to lack of support for this mode between the from and to locations).
When this happens I want to skip this row pair, input one more line in tempos_falta_ubs
(with NA in all columns) and go ahead to the next. I'm doing this manually, but it sucks. How can I do this automatically without stop the looping?
Thanks in advance.
empty_line <- structure(list(
from_addresses = NA_character_, to_addresses = NA_character_,
distances = NA_integer_, duration = NA_integer_, currency = NA, fare = NA
), .Names = c("from_addresses", "to_addresses", "distances", "duration", "currency", "fare"),
row.names = "NA", class = "data.frame")
for (linha in seq_len(nrow(fluxo))) {
origin <- fluxo[linha, 3:4]
destiny <- fluxo[linha, 5:6]
x <- tryCatch(dist_google(from=origin, to=destiny, mode='walking'), error = function(e) empty_line)
tempos_falta_ubs <- rbind(tempos_falta_ubs, x)
}