Reputation: 3805
I make a call to an API by proving a latitude longitude as shown below
library(httr)
headers = c(
'Content-Type' = 'application/json'
)
body = '{
"locations": [
{"latitude": -37.916919, "longitude": 145.146892},
],
"scenarios": ["x1", "x2", "x3", "x4"],
"hazards": ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"],
"years": ["1", "2", "3", "4", "5", "6", "7", "8"]
}'
res <- VERB("POST",
url = "https://xxx", body = body, add_headers(headers))
If I have a dataframe of lat,lon as shown below:
dat <-
structure(list(id = c(143L, 147L, 148L, 293L, 346L, 358L, 374L, 382L, 387L, 388L),
latitude = c(-37.916919, -36.106951, -37.839613, -32.897738, -28.73769167, -27.8675, -28.064616, -28.016, -27.593, -27.648988),
longitude = c(145.146892, 146.890143, 145.278376, 151.777484, 140.3534722, 139.6925, 139.538703, 139.692, 139.506, 139.458764)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
How can I send each lat/lon in a for-loop to get the results back.
Upvotes: 0
Views: 52
Reputation: 24722
How about making a function that takes lat
and long
, and use apply
over the rows of your data.frame?
get_result <- function(lat,long) {
headers = c('Content-Type' = 'application/json')
body = paste0('{
"locations": [
{"latitude": ', lat, ', "longitude": ', long, '},
],
"scenarios": ["x1", "x2", "x3", "x4"],
"hazards": ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"],
"years": ["1", "2", "3", "4", "5", "6", "7", "8"]
}')
VERB("POST", url = "https://xxx", body = body, add_headers(headers))
}
apply(dat,1,\(i) get_result(i[2], i[3]))
Upvotes: 1