Skip to content

Instantly share code, notes, and snippets.

@lvalnegri
Last active April 1, 2021 16:13
Show Gist options
  • Save lvalnegri/b594ea1005517ece9a045a25e7a5fbfc to your computer and use it in GitHub Desktop.
Save lvalnegri/b594ea1005517ece9a045a25e7a5fbfc to your computer and use it in GitHub Desktop.
pkgs <- c('data.table', 'httr', 'jsonlite')
lapply(pkgs, require, char = TRUE)
get_catch_postcodes <- function(x_lon, y_lat, tm = 120){
# <tm> input travel time is in minutes
# output travel time is in seconds
# output travel distance is in metres
appId <- 'INSERT HERE YOUR ID'
apiKey <- 'INSERT HERE YOUR API KEY'
requestBody <- paste0('{
"arrival_searches" : [{
"id" : "catchment areas",
"coords": {"lat":', y_lat, ', "lng":', x_lon,' },
"transportation" : {"type" : "driving"} ,
"arrival_time" : "2018-09-20T19:00:00Z",
"travel_time" : ', tm * 60, ',
"properties": ["travel_time", "distance"]
}]
}')
y <- POST(
url = "http://api.traveltimeapp.com/v4/time-filter/postcodes",
add_headers('Content-Type' = 'application/json'),
add_headers('Accept' = 'application/json'),
add_headers('X-Application-Id' = appId),
add_headers('X-Api-Key' = apiKey),
body = requestBody,
encode = "json"
)
y <- fromJSON(as.character(y))
y1 <- unlist(y$results$postcodes[[1]]$properties)
y <- data.table(
'postcode' = y$results$postcodes[[1]]$code,
'time' = y1[names(y1) == 'travel_time'],
'distance' = y1[names(y1) == 'distance']
)
y[order(time, distance)]
}
# load data
places <- read_fst(file.path(path, 'places'), as.data.table = TRUE)
postcodes <- read_fst(file.path(geo_path, 'postcodes'), columns = c('postcode', 'OA'), as.data.table = TRUE)
# download driving data
dts <- NULL
for(idx in 1:nrow(places)){
message('Calculating values for ', places[idx, name], ' with id ', places[idx, place_id])
y <- get_catch_postcodes(places[idx, x_lon], places[idx, y_lat])
dts <- rbindlist(list( dts, data.table('place_id' = places[idx, place_id], y) ))
Sys.sleep(2)
}
# normalize postcode
dts[nchar(postcode) == 8, postcode := gsub(' ', '', postcode)]
dts[nchar(postcode) == 6, postcode := gsub(' ', ' ', postcode)]
# add OA
dts <- postcodes[dts, on = 'postcode']
dts <- dts[!is.na(OA)]
# add time class
max_time <- max(dts$time)/60
dtime <- 15
dts[, ctime := cut(
time / 60,
seq(0, max_time, dtime),
paste0('(', seq(0, max_time - dtime, dtime), '-', seq(dtime, max_time, dtime), ']'),
ordered = TRUE
)]
# add distance class
max_dist <- ceiling(max(dts$distance/10000, na.rm = TRUE)) * 10
cuts <- c(0, 2, 5, 10, 25, seq(50, max_dist, 50))
if(max_dist > cuts[length(cuts)]) cuts <- c(cuts, cuts[length(cuts)] + 50)
dts[, cdistance := cut(
distance / 1000,
cuts,
sapply(2:length(cuts), function(x) paste0('(', cuts[x-1], '-', cuts[x], ']')),
ordered = TRUE
)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment