library(tidyverse)
library(tmap)
library(ggplot2)
library(units)
library(sf)
library(leaflet)
library(tidycensus)
library(leafsync)
library(dbscan)
library(sfnetworks)
library(tigris)
library(tidygraph)
library(plotly)
library(osmdata)
library(here)
library(tidytransit)
library(units)
library(leaflet)
library(tidycensus)
library(leafsync)
epsg <- 4326
Download census tract data for API request
census_api_key(Sys.getenv("census_api"))
## To install your API key for use in future sessions, run this function with `install = TRUE`.
#### Tract polygons for the Yelp query
# tract <- suppressMessages(
# get_acs(geography = "tract", # or "block group", "county", "state" etc.
# state = "SC",
# county = c("charleston"),
# variables = c(hhincome = 'B19019_001',
# race.tot = "B02001_001",
# race.white = "B02001_002",
# race.black = 'B02001_003'
# ),
# year = 2021,
# survey = "acs5", # American Community Survey 5-year estimate
# geometry = TRUE, # returns sf objects
# output = "wide") # wide vs. long
# )
# Save downloaded census data to a file
# saveRDS(tract, "charleston_tract.rds")
tract_char <- read_rds("charleston_tract.rds")
charleston <- places('SC') %>%
filter(NAME == 'Charleston')
## Retrieving data for the year 2021
##
|
| | 0%
|
| | 1%
|
|= | 1%
|
|= | 2%
|
|== | 2%
|
|== | 3%
|
|=== | 4%
|
|=== | 5%
|
|==== | 5%
|
|==== | 6%
|
|===== | 7%
|
|===== | 8%
|
|====== | 8%
|
|====== | 9%
|
|======= | 10%
|
|============= | 18%
|
|============= | 19%
|
|============== | 20%
|
|============== | 21%
|
|=============== | 21%
|
|=============== | 22%
|
|================ | 22%
|
|================ | 23%
|
|================ | 24%
|
|================= | 24%
|
|================= | 25%
|
|================== | 25%
|
|================== | 26%
|
|=================== | 26%
|
|=================== | 27%
|
|=================== | 28%
|
|==================== | 28%
|
|==================== | 29%
|
|===================== | 29%
|
|===================== | 30%
|
|====================== | 31%
|
|====================== | 32%
|
|======================= | 32%
|
|======================= | 33%
|
|======================== | 34%
|
|======================== | 35%
|
|========================= | 35%
|
|========================= | 36%
|
|========================== | 36%
|
|========================== | 37%
|
|========================== | 38%
|
|=========================== | 38%
|
|=========================== | 39%
|
|============================ | 39%
|
|============================ | 40%
|
|============================= | 41%
|
|============================= | 42%
|
|============================== | 42%
|
|============================== | 43%
|
|=============================== | 44%
|
|=============================== | 45%
|
|================================ | 45%
|
|================================ | 46%
|
|================================= | 47%
|
|================================= | 48%
|
|================================== | 48%
|
|================================== | 49%
|
|=================================== | 49%
|
|=================================== | 50%
|
|=================================== | 51%
|
|==================================== | 51%
|
|==================================== | 52%
|
|===================================== | 52%
|
|===================================== | 53%
|
|====================================== | 54%
|
|====================================== | 55%
|
|======================================= | 55%
|
|======================================= | 56%
|
|======================================== | 57%
|
|======================================== | 58%
|
|========================================= | 58%
|
|========================================= | 59%
|
|========================================== | 59%
|
|========================================== | 60%
|
|========================================== | 61%
|
|=========================================== | 61%
|
|=========================================== | 62%
|
|============================================ | 62%
|
|============================================ | 63%
|
|============================================= | 64%
|
|============================================= | 65%
|
|============================================== | 65%
|
|============================================== | 66%
|
|=============================================== | 67%
|
|=============================================== | 68%
|
|================================================ | 68%
|
|================================================ | 69%
|
|================================================= | 70%
|
|================================================= | 71%
|
|================================================== | 71%
|
|================================================== | 72%
|
|=================================================== | 72%
|
|=================================================== | 73%
|
|==================================================== | 74%
|
|==================================================== | 75%
|
|===================================================== | 75%
|
|===================================================== | 76%
|
|====================================================== | 77%
|
|====================================================== | 78%
|
|======================================================= | 78%
|
|======================================================= | 79%
|
|======================================================== | 80%
|
|======================================================== | 81%
|
|========================================================= | 81%
|
|========================================================= | 82%
|
|========================================================== | 82%
|
|========================================================== | 83%
|
|========================================================== | 84%
|
|=========================================================== | 84%
|
|=========================================================== | 85%
|
|============================================================ | 85%
|
|============================================================ | 86%
|
|============================================================= | 86%
|
|============================================================= | 87%
|
|============================================================= | 88%
|
|============================================================== | 88%
|
|============================================================== | 89%
|
|=============================================================== | 89%
|
|=============================================================== | 90%
|
|================================================================ | 91%
|
|================================================================ | 92%
|
|================================================================= | 92%
|
|================================================================= | 93%
|
|================================================================== | 94%
|
|================================================================== | 95%
|
|=================================================================== | 95%
|
|=================================================================== | 96%
|
|==================================================================== | 96%
|
|==================================================================== | 97%
|
|==================================================================== | 98%
|
|===================================================================== | 98%
|
|===================================================================== | 99%
|
|======================================================================| 99%
|
|======================================================================| 100%
# char_city <- tract_char[charleston,]
# Save Charleston city census data to a file
# saveRDS(char_city, "charlestoncity_tract.rds")
charcity_tract <- read_rds("charlestoncity_tract.rds")
#View the geographic boundary
charcity_tract <- charcity_tract %>%
select(GEOID,
hhincome = hhincomeE, # New name = old name
race.tot = race.totE,
race.white = race.whiteE,
race.black = race.blackE)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'darkred')
# Repeat exercise in mini assignment 1 to request yelp data
library(httr)
##
## Attaching package: 'httr'
## The following object is masked from 'package:plotly':
##
## config
library(jsonlite)
##
## Attaching package: 'jsonlite'
## The following object is masked from 'package:purrr':
##
## flatten
library(reshape2)
##
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
##
## smiths
library(yelpr)
library(knitr)
# Data would be written into .rds file after requesting and,
# the code chunks for yelp API request would be commented out
# Function: Get tract-wise radius
get_r <- function(poly, epsg_id){
#---------------------
# Takes: a single POLYGON or LINESTRTING
# Outputs: distance between the centroid of the boundingbox and a corner of the bounding box
#---------------------
# Get bounding box of a given polygon
bb <- st_bbox(poly)
# Get lat & long coordinates of any one corner of the bounding box.
bb_corner <- st_point(c(bb[1], bb[2])) %>% st_sfc(crs = epsg_id)
# Get centroid of the bb
bb_center_x <- (bb[3]+bb[1])/2
bb_center_y <- (bb[4]+bb[2])/2
bb_center <- st_point(c(bb_center_x, bb_center_y)) %>% st_sfc(crs = epsg_id) %>% st_sf()
# Get the distance between bb_p and c
r <- st_distance(bb_corner, bb_center)
# Multiply 1.1 to make the circle a bit larger than the Census Tract.
# See the Yelp explanation of their radius parameter to see why we do this.
bb_center$radius <- r*1.2
return(bb_center)
}
r4all_apply <- charcity_tract %>%
st_geometry() %>%
st_transform(crs = epsg) %>%
lapply(., function(x) get_r(x, epsg_id = epsg))
r4all_apply <- bind_rows(r4all_apply)
ready_4_yelp <- r4all_apply %>%
mutate(x = st_coordinates(.)[,1],
y = st_coordinates(.)[,2])
# FUNCTION
get_yelp <- function(tract, category){
# ----------------------------------
# Gets one row of tract information (1,) and category name (str),
# Outputs a list of business data.frame
Sys.sleep(1)
n <- 1
# First request --------------------------------------------------------------
resp <- business_search(api_key = Sys.getenv("yelpr_api"),
categories = category,
latitude = tract$y,
longitude = tract$x,
offset = (n - 1) * 50, # = 0 when n = 1
radius = round(tract$radius),
limit = 50)
# Calculate how many requests are needed in total
required_n <- ceiling(resp$total/50)
# out is where the results will be appended to.
out <- vector("list", required_n)
# Store the business information to nth slot in out
out[[n]] <- resp$businesses
# Change the name of the elements to the total required_n
# This is to know if there are more than 1000 businesses,
# we know how many.
names(out)[n] <- required_n
# Throw error if more than 1000
if (resp$total >= 1000)
{
# glue formats string by inserting {n} with what's currently stored in object n.
print(glue::glue("{n}th row has >= 1000 businesses."))
# Stop before going into the loop because we need to
# break down Census Tract to something smaller.
return(out)
}
else
{
# add 1 to n
n <- n + 1
# Now we know required_n -----------------------------------------------------
# Starting a loop
while(n <= required_n){
resp <- business_search(api_key = Sys.getenv("yelpr_api"),
categories = category,
latitude = tract$y,
longitude = tract$x,
offset = (n - 1) * 50,
radius = round(tract$radius),
limit = 50)
out[[n]] <- resp$businesses
n <- n + 1
} #<< end of while loop
# Merge all elements in the list into a single data frame
out <- out %>% bind_rows()
return(out)
}
}
# Prepare a collector
yelp_all_list <- vector("list", nrow(ready_4_yelp))
# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
yelp_all_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "restaurants"))
if (row %% 10 == 0){
print(paste0("Current row: ", row))
}
}
# Collapsing the list into a data.frame
eatinchar_yelp <- yelp_all_list %>% bind_rows() %>% as_tibble()
# print
eatinchar_yelp %>% print(width=1000)
# Save before-tidied yelp_mediterra to a file
# saveRDS(eatinchar_yelp, "eatinchar_yelp_raw.rds")
eatinchar_yelp_raw <- read_rds("eatinchar_yelp_raw.rds")
# Flatten
# Custom function that takes the data frame in "categories" column in Yelp data
# and returns a character vector
concate_list <- function(x){
# x is a data frame with columns "alias" and "title" from Yelp$categories
# returns a character vector containing category concatenated titles
titles <- x[["title"]] %>% str_c(collapse = ", ")
return(titles)
}
eatinchar_yelp_clean <- eatinchar_yelp_raw %>%
distinct(id, .keep_all=T) %>%
jsonlite::flatten() %>%
# 2. Handling list-columns
mutate(transactions = transactions %>%
map_chr(., function(x) str_c(x, collapse=", ")),
location.display_address = location.display_address %>%
map_chr(., function(x) str_c(x, collapse=", ")),
categories = categories %>% map_chr(concate_list))
# Check missing values
eatinchar_yelp_clean %>%
map_dbl(., function(x) sum(is.na(x))) %>%
# map_dbl is a variant of map() which outputs
# numeric vector rather than a list.
sapply(., function(x) x != 0) %>%
which()
## price location.address1 location.address2 location.address3
## 11 17 18 19
eatinchar_yelp_sf <- eatinchar_yelp_clean %>%
st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"),
crs = 4326)
tm_shape(eatinchar_yelp_sf %>% filter(review_count>500 & rating>3)) +
tm_symbols(col = "review_count",
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=1,
legend.shape.show = FALSE,
legend.size.is.portrait = TRUE,
shapes.legend = 22,
group = "cat",
id = "name",
popup.vars = c("Rating"="rating",
"No.of Reviews"="review_count",
"Offer"="categories")) +
tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.
st_crs(charleston) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
eatwithinchar_yelp_sf <- eatinchar_yelp_sf[charleston, ,op = st_intersects]
tm_shape(eatwithinchar_yelp_sf %>% filter(review_count>500 & rating>3)) +
tm_symbols(col = "review_count",
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=1,
legend.shape.show = FALSE,
legend.size.is.portrait = TRUE,
shapes.legend = 22,
group = "cat",
id = "name",
popup.vars = c("Rating"="rating",
"No.of Reviews"="review_count",
"Offer"="categories")) +
tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.
Download Required data from OSM.
osm_road <- opq(bbox = st_bbox(charleston)) %>%
add_osm_feature(key = 'highway',
value = c("motorway", "trunk", "primary", "secondary", "tertiary",
"residential", "motorway_link", "trunk_link", "primary_link",
"secondary_link", "tertiary_link", "residential_link",
"unclassified")) %>%
osmdata_sf() %>%
osm_poly2line()
names(osm_road)
## [1] "bbox" "overpass_call" "meta"
## [4] "osm_points" "osm_lines" "osm_polygons"
## [7] "osm_multilines" "osm_multipolygons"
osm <- osm_road$osm_line %>%
select(osm_id, highway) %>%
sfnetworks::as_sfnetwork(directed = FALSE) %>%
activate("edges") %>%
filter(!edge_is_multiple()) %>%
filter(!edge_is_loop()) %>%
convert(., sfnetworks::to_spatial_subdivision) %>%
# rename_all(~gsub(":", "_", .)) %>%
convert(., sfnetworks::to_spatial_smooth)
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
# Add a new column named 'length' to the edges part of the object `osm`.
osm <- osm %>% mutate(length = edge_length())
# Plot
# before_net <- osm %>%
# activate("nodes") %>%
# mutate(custom_id = seq(1, osm %>% st_as_sf("nodes") %>% nrow()),
# is.new = case_when(is.na(.tidygraph_node_index) ~ "new nodes",
# TRUE ~ "existing nodes"),
# is.new = factor(is.new))
#
# pal <- colorFactor(palette = c("yellow", "red"), domain = before_net %>% st_as_sf("nodes") %>% pull(is.new))
osm_before_map <- leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
setView( -79.940918, 32.784618, zoom = 14) %>%
# zooming in to show more details
addPolylines(data = osm %>% st_as_sf('edges'), col = "grey", weight = 3, opacity = 0.9) %>%
addCircles(data = osm %>% st_as_sf('nodes'), fillColor = "orange", stroke = F, radius = 20, fillOpacity = 0.7)
# %>% addLegend(position = "bottomright", pal = pal, values = before_net %>% st_as_sf("nodes") %>% pull(is.new))
osm_before_map
# Reference code borrwoed from mini assignment 3
# store_dist <- st_distance(tract_q5, bikerent_atl) %>%
# as.data.frame()
#
# # st_distance calculated the distance from each tract to each store, returning a (162*7) table
# # extract the least number from each row as a vector of "shortest distance"
# shortest_dist <- rep(NA, times=nrow(tract_q5))
#
# for (i in 1:nrow(tract_q5))
# {
# shortest_dist[i] <- min(store_dist[i,])
# }
#
# # add "shortest distance to column" (unit is meter)
# tract_q5$shortest.m <- shortest_dist
Step 4. Try the simulation for just one home location as a pilot
test.
home <- r4all_apply
# Extract the first row from `home` object and store it as `origin`
origin <- home[1,]
# Find a restaurant with the most review counts among all the ones having rating over or equal to 4.5
pop_eat <- eatwithinchar_yelp_sf %>%
filter(rating>=4.5) %>%
filter(review_count==max(review_count))
# Find the shortest path from origin to station
# using st_network_paths() function.
paths <- st_network_paths(osm, from = origin, to = pop_eat, type = "shortest")
# Calculate the length of edges in the shortest route to the popular restaurant selected
closest_dist <- osm %>%
activate("nodes") %>%
# Slice the part that corresponds with the shortest route
slice(paths$node_paths[[1]]) %>%
# Extract "edges" from the sfnetworks object as a separate sf object
st_as_sf("edges") %>%
# Extract 'length' column and calculate sum
pull(length) %>%
sum()
# If the routing function is not working, assume the route length is 150% of Euclidean distance
# if (closest_dist == set_units(0, m)){
# closest_dist <- ??? * 1.5
# }
# Calculate how to long it takes to traverse `closest_dist`
# assuming we drive at 30 miles/hour speed.
# Store the output in `trvt_osm_m`.
car_speed <- set_units(30, mile/h)
trvt_osm_m <- closest_dist/set_units(car_speed, m/min) %>% # Distance divided by 30 mile/h
as.vector(.)
# 1. From `osm` object, activate nodes part and
# 2. use `closest_index` to extract the selected path
paths_closest <- osm %>%
activate("nodes") %>%
slice(paths$node_paths[[1]])
# Visualize
leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
setView( -79.940918, 32.784618, zoom = 14) %>%
# zooming in to show more details
# Base network in grey
addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>%
# Chosen edges
addPolylines(data = paths_closest %>% st_as_sf("edges"), color = "red", weight = 10, opacity = 0.5) %>%
# Chosen nodes
addCircles(data = paths_closest %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 50)
flooded_char <- read_sf(here("floodedcharv2","flooded_char-v2.shp"))
flooded_char %>%
ggplot() +
geom_sf()

before_char <- osm_road$osm_lines
after_char <- before_char[flooded_char, ]
# flooded_char_v2 <- read_sf(here("uaproj0.0","floodedcharleston","char_flooded_vec.shp"))
# flooded_char_v2 %>%
# ggplot() +
# geom_sf()
# after_char_v2 <- before_char[flooded_char_v2, ]
after_char_road <- before_char[!(before_char$osm_id %in% after_char$osm_id), ]
osm_after <- after_char_road %>%
select(osm_id, highway) %>%
sfnetworks::as_sfnetwork(directed = FALSE) %>%
activate("edges") %>%
filter(!edge_is_multiple()) %>%
filter(!edge_is_loop()) %>%
convert(., sfnetworks::to_spatial_subdivision) %>%
# rename_all(~gsub(":", "_", .)) %>%
convert(., sfnetworks::to_spatial_smooth)
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
# Add a new column named 'length' to the edges part of the object `osm`.
osm_after <- osm_after %>% mutate(length = edge_length())
# Plot
# after_net <- osm_after %>%
# activate("nodes") %>%
# mutate(custom_id = seq(1, osm_after %>% st_as_sf("nodes") %>% nrow()),
# is.new = case_when(is.na(.tidygraph_node_index) ~ "new nodes",
# TRUE ~ "existing nodes"),
# is.new = factor(is.new))
#
# pal <- colorFactor(palette = c("yellow", "red"), domain = after_net %>% st_as_sf("nodes") %>% pull(is.new))
osm_after_map <- leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
setView( -79.940918, 32.784618, zoom = 14) %>%
# zooming in to show more details
addPolylines(data = osm_after %>% st_as_sf('edges'), col = "grey", weight = 3, opacity = 0.9) %>%
addCircles(data = osm_after %>% st_as_sf('nodes'), fillColor = "orange", stroke = F, radius = 20, fillOpacity = 0.7)
# %>% addLegend(position = "bottomright", pal = pal, values = after_net %>% st_as_sf("nodes") %>% pull(is.new))
osm_after_map
# Find the shortest path from origin to station
# using st_network_paths() function.
paths_after <- st_network_paths(osm_after, from = origin, to = pop_eat, type = "shortest")
## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.
# Calculate the length of edges in the shortest route to the popular restaurant selected
closest_dist_after <- osm_after %>%
activate("nodes") %>%
# Slice the part that corresponds with the shortest route
slice(paths_after$node_paths[[1]]) %>%
# Extract "edges" from the sfnetworks object as a separate sf object
st_as_sf("edges") %>%
# Extract 'length' column and calculate sum
pull(length) %>%
sum()
# If the routing function is not working, assume the route length is 150% of Euclidean distance
# if (closest_dist_after == set_units(0, m)){
# closest_dist_after <- ??? * 1.5
# }
# Calculate how to long it takes to traverse `closest_dist`
# assuming we drive at 30 miles/hour speed.
# Store the output in `trvt_osm_m`.
car_speed_after <- set_units(30, mile/h)
trvt_osm_m_after <- closest_dist_after/set_units(car_speed, m/min) %>% # Distance divided by 30 mile/h
as.vector(.)
# 1. From `osm` object, activate nodes part and
# 2. use `closest_index` to extract the selected path
paths_closest_after <- osm_after %>%
activate("nodes") %>%
slice(paths_after$node_paths[[1]])
# pop_eat <- eatwithinchar_yelp_sf %>%
# filter(rating>=4.5) %>%
# filter(review_count==max(review_count))
# Find the shortest path from origin to station
# using st_network_paths() function.
paths_all_after <- st_network_paths(osm_after, from = origin, to = eatwithinchar_yelp_sf, type = "shortest")
## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.
# # Calculate the length of edges in the shortest route to the popular restaurant selected
# closest_dist_after <- osm_after %>%
# activate("nodes") %>%
# # Slice the part that corresponds with the shortest route
# slice(paths_after$node_paths[[1]]) %>%
# # Extract "edges" from the sfnetworks object as a separate sf object
# st_as_sf("edges") %>%
# # Extract 'length' column and calculate sum
# pull(length) %>%
# sum()
#
# # If the routing function is not working, assume the route length is 150% of Euclidean distance
# # if (closest_dist_after == set_units(0, m)){
# # closest_dist_after <- ??? * 1.5
# # }
#
# # Calculate how to long it takes to traverse `closest_dist`
# # assuming we drive at 30 miles/hour speed.
# # Store the output in `trvt_osm_m`.
# car_speed_after <- set_units(30, mile/h)
# trvt_osm_m_after <- closest_dist_after/set_units(car_speed, m/min) %>% # Distance divided by 30 mile/h
# as.vector(.)
#
lengthIs <- function(n) function(x) length(x)>n
# Filter(lengthIs(0), paths_all_after$edge_paths)
paths_exists_after <- paths_all_after %>%
filter(edge_paths %in% Filter(lengthIs(0), paths_all_after$edge_paths))
# 1. From `osm` object, activate nodes part and
# 2. use `closest_index` to extract the selected path
paths_left_after <- osm_after %>%
activate("nodes") %>%
slice(paths_exists_after$node_paths[[1]])
# Visualize
leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
setView( -79.940918, 32.784618, zoom = 14) %>%
# zooming in to show more details
# Base network in grey
addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>%
# Chosen edges
addPolylines(data = paths_left_after %>% st_as_sf("edges"), color = "red", weight = 10, opacity = 0.5)
# %>%
# Chosen nodes
# addCircles(data = paths_closest %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 50)