You may also need to include other variables. You may use older Census boundary (e.g., 2019) to reduce the number of Yelp API queries in Step 3.
#load census API key
library(tidycensus)
census_api_key(Sys.getenv("census_api"))
## To install your API key for use in future sessions, run this function with `install = TRUE`.
#load other helpful libraries
library(sf)
## Linking to GEOS 3.10.2, GDAL 3.4.1, PROJ 8.2.1; sf_use_s2() is TRUE
library(tmap)
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, will retire in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
## The sp package is now running under evolution status 2
## (status 2 uses the sf package in place of rgdal)
library(jsonlite)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.2 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ purrr::flatten() masks jsonlite::flatten()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(httr)
library(jsonlite)
library(reshape2)
##
## Attaching package: 'reshape2'
##
## The following object is masked from 'package:tidyr':
##
## smiths
library(here)
## here() starts at /home/rstudio
library(yelpr)
library(knitr)
library(tigris)
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
# Tract polygons for the Yelp query
tract <- suppressMessages(
get_acs(geography = "tract", # or "block group", "county", "state" etc.
state = "GA",
county = c("Fulton", "Dekalb"),
variables = c(hhincome = 'B19019_001',
race.tot = "B02001_001",
race.white = "B02001_002",
race.black = 'B02001_003',
trans.total = "B08006_001",
trans.bicycle = "B08006_014",
commute.total = "B08301_001",
commute.bicycle = "B08301_018"
),
year = 2019,
survey = "acs5", # American Community Survey 5-year estimate
geometry = TRUE, # returns sf objects
output = "wide") # wide vs. long
)
##
|
| | 0%
|
|= | 1%
|
|= | 2%
|
|== | 3%
|
|=== | 4%
|
|==== | 5%
|
|==== | 6%
|
|===== | 7%
|
|====== | 8%
|
|====== | 9%
|
|======= | 10%
|
|======= | 11%
|
|======== | 12%
|
|========= | 13%
|
|========== | 14%
|
|=========== | 15%
|
|=========== | 16%
|
|============== | 21%
|
|=============== | 21%
|
|================ | 22%
|
|================ | 23%
|
|================= | 25%
|
|================== | 26%
|
|=================== | 27%
|
|=================== | 28%
|
|==================== | 29%
|
|===================== | 30%
|
|====================== | 31%
|
|======================= | 32%
|
|======================= | 33%
|
|======================== | 34%
|
|========================= | 36%
|
|====================================== | 54%
|
|=========================================== | 61%
|
|=========================================== | 62%
|
|============================================ | 63%
|
|============================================================ | 85%
|
|============================================================ | 86%
|
|============================================================== | 89%
|
|================================================================= | 93%
|
|======================================================================| 100%
atlanta <- places('GA', year = 2019) %>%
filter(NAME == 'Atlanta')
##
|
| | 0%
|
|= | 1%
|
|= | 2%
|
|== | 2%
|
|== | 3%
|
|=== | 4%
|
|=== | 5%
|
|==== | 5%
|
|==== | 6%
|
|===== | 7%
|
|===== | 8%
|
|====== | 8%
|
|====== | 9%
|
|======= | 11%
|
|======== | 12%
|
|========= | 12%
|
|========= | 13%
|
|========== | 14%
|
|========== | 15%
|
|=========== | 15%
|
|=========== | 16%
|
|============ | 17%
|
|============ | 18%
|
|============= | 18%
|
|============= | 19%
|
|================== | 25%
|
|================== | 26%
|
|=================== | 27%
|
|=================== | 28%
|
|==================== | 28%
|
|==================== | 29%
|
|===================== | 29%
|
|===================== | 30%
|
|===================== | 31%
|
|====================== | 31%
|
|====================== | 32%
|
|======================= | 32%
|
|======================= | 33%
|
|======================= | 34%
|
|======================== | 34%
|
|======================== | 35%
|
|========================= | 35%
|
|========================= | 36%
|
|========================== | 37%
|
|=========================== | 38%
|
|=============================== | 45%
|
|================================ | 45%
|
|================================ | 46%
|
|================================= | 46%
|
|================================= | 47%
|
|================================== | 48%
|
|================================== | 49%
|
|=================================== | 49%
|
|=================================== | 50%
|
|==================================== | 52%
|
|======================================== | 58%
|
|========================================= | 58%
|
|========================================= | 59%
|
|========================================== | 60%
|
|=========================================== | 61%
|
|=========================================== | 62%
|
|============================================ | 62%
|
|============================================ | 63%
|
|============================================= | 64%
|
|============================================= | 65%
|
|============================================== | 66%
|
|=============================================== | 67%
|
|================================================= | 70%
|
|================================================== | 72%
|
|=================================================== | 73%
|
|==================================================== | 74%
|
|==================================================== | 75%
|
|===================================================== | 75%
|
|===================================================== | 76%
|
|====================================================== | 77%
|
|====================================================== | 78%
|
|======================================================= | 78%
|
|======================================================= | 79%
|
|======================================================== | 79%
|
|======================================================== | 80%
|
|========================================================= | 81%
|
|========================================================== | 83%
|
|=========================================================== | 84%
|
|============================================================== | 88%
|
|============================================================== | 89%
|
|=============================================================== | 90%
|
|================================================================ | 91%
|
|================================================================ | 92%
|
|================================================================= | 92%
|
|======================================================================| 100%
tract <- tract[atlanta,]
# Retaining only those I want.
tract <- tract %>%
select(GEOID,
hhincome = hhincomeE, # New name = old name
race.tot = race.totE,
race.white = race.whiteE,
race.black = race.blackE,
trans.total = trans.totalE,
trans.bicycle = trans.bicycleE,
commute.total = commute.totalE,
commute.bicycle = commute.bicycleE)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tract) + tm_borders() + tm_shape(atlanta) + tm_borders(col = 'darkred', lw = 2)
summary(tract)
## GEOID hhincome race.tot race.white
## Length:162 Min. : 12485 Min. : 0 Min. : 0.0
## Class :character 1st Qu.: 32064 1st Qu.: 2518 1st Qu.: 180.8
## Mode :character Median : 60333 Median : 3854 Median :1021.5
## Mean : 67701 Mean : 4090 Mean :1692.0
## 3rd Qu.: 88096 3rd Qu.: 5218 3rd Qu.:3110.8
## Max. :208750 Max. :16329 Max. :7417.0
## NA's :3
## race.black trans.total trans.bicycle commute.total
## Min. : 0 Min. : 0 Min. : 0.00 Min. : 0
## 1st Qu.: 640 1st Qu.:1086 1st Qu.: 0.00 1st Qu.:1086
## Median : 1414 Median :1816 Median : 0.00 Median :1816
## Mean : 2072 Mean :2084 Mean : 20.22 Mean :2084
## 3rd Qu.: 2604 3rd Qu.:2869 3rd Qu.: 23.00 3rd Qu.:2869
## Max. :15337 Max. :7990 Max. :225.00 Max. :7990
##
## commute.bicycle geometry
## Min. : 0.00 MULTIPOLYGON :162
## 1st Qu.: 0.00 epsg:4269 : 0
## Median : 0.00 +proj=long...: 0
## Mean : 20.22
## 3rd Qu.: 23.00
## Max. :225.00
##
# Notice that there are some missing values in household income and race.tot
tract %>% filter(is.na(hhincome)&race.tot==0) %>% as_tibble()
## # A tibble: 2 × 10
## GEOID hhincome race.tot race.white race.black trans.total trans.bicycle
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 13089980000 NA 0 0 0 0 0
## 2 13121980000 NA 0 0 0 0 0
## # ℹ 3 more variables: commute.total <dbl>, commute.bicycle <dbl>,
## # geometry <MULTIPOLYGON [°]>
# Test if the census data-set has duplicated geographic data
# Extract "NA" geometries
tract_na <- tract %>% filter(is.na(hhincome)&race.tot==0)
# Retain "non-NA" geometries
tract_sub <- tract %>% filter(!(is.na(hhincome)&race.tot==0))
# See if two geometires have overlapped areas to intersect
test_na <- tract_sub[tract_na, ]
It is surprising that the 2 geometries “intersected”. However, if we compare the computer-output the intersected area and the expected overlapping areas (which is tract_na)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(test_na) + tm_borders(col = 'navy', lw = 3) + tm_fill(col = 'magenta') + tm_shape(tract_na) + tm_borders(col = 'cyan')
They are not identical at all.
View the tract_sub and tract_na together on the map, they are not overlapped. So, even though the requested census data-set have rows without actual data, they are still non-replicated geometries.
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tract_sub) + tm_borders(col = 'navy', lw = 3) + tm_fill(col = 'magenta') + tm_shape(tract_na) + tm_borders(col = 'cyan')
If you encounter issues with Queries-Per-Second limit, try Sys.sleep() as you see appropriate. Remember to save the downloaded Yelp data (e.g., as .RData format) in your hard drive to avoid making excessive API requests. Once you’ve saved the data, you can simply read the Yelp data from your hard drive and proceed from there. However, even when you’ve stopped using the code for downloading Yelp data, do not delete them from your RMD; instructors need to see the entire code. You can use code chunk option {r, eval=FALSE} to keep the code for downloading Yelp in your RMD but not actually run it. Read this to learn more.
# Repeat exercise in mini assignment 1 to request yelp data
# 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)
}
epsg_id <- 4326
r4all_apply <- tract %>%
st_geometry() %>%
st_transform(crs = epsg_id) %>%
lapply(., function(x) get_r(x, epsg_id = epsg_id))
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,], "bikerentals"))
if (row %% 10 == 0){
print(paste0("Current row: ", row))
}
}
# Collapsing the list into a data.frame
yelp_bikerent <- yelp_all_list %>% bind_rows() %>% as_tibble()
# Save before-tidied yelp_bikerent to a file
# saveRDS(yelp_bikerent, "yelp_bikerent_raw.rds")
# Read saved .rds file
bikerent_raw <- read_rds("yelp_bikerent_raw.rds")
Deleting duplicated rows. Flattening nested columns that have multiple variables in one column. Pay particular attention to the “category” column. Delete rows that have missing data in coordinates variable and other variables of interest. It’s okay to have NAs in variables that are not of interest. Delete rows that fall outside of the City of Atlanta boundary.
# Deleting duplicated rows
bikerent_unique <- bikerent_raw %>%
distinct(id, .keep_all=T)
glue::glue("Before dropping duplicated rows, there were {nrow(bikerent_raw)} rows. After dropping them, there are {nrow(bikerent_unique)} rows") %>%
print()
## Before dropping duplicated rows, there were 92 rows. After dropping them, there are 11 rows
# Take a glimpse of the unique data set
glimpse(bikerent_unique)
## Rows: 11
## Columns: 16
## $ id <chr> "JkkHRgYj0mvdgbMXFm436w", "FK7-M9BGyCgpEmVifcPfoA", "Umf…
## $ alias <chr> "civil-bikes-atlanta", "aztec-cycles-stone-mountain", "j…
## $ name <chr> "Civil Bikes", "Aztec Cycles", "JUMP", "Atlanta Bicycle …
## $ image_url <chr> "https://s3-media4.fl.yelpcdn.com/bphoto/JqTLT-chrqtbyuo…
## $ is_closed <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, …
## $ url <chr> "https://www.yelp.com/biz/civil-bikes-atlanta?adjust_cre…
## $ review_count <int> 11, 61, 1, 128, 103, 42, 15, 20, 1, 68, 12
## $ categories <list> [<data.frame[2 x 2]>], [<data.frame[3 x 2]>], [<data.fra…
## $ rating <dbl> 4.5, 5.0, 1.0, 4.5, 4.0, 4.5, 4.5, 4.5, 1.0, 4.5, 2.0
## $ coordinates <df[,2]> <data.frame[11 x 2]>
## $ transactions <list> [], [], [], [], [], [], [], [], [], [], []
## $ location <df[,8]> <data.frame[11 x 8]>
## $ phone <chr> "+14043238754", "+16786369043", "+18333006106", "+17708…
## $ display_phone <chr> "(404) 323-8754", "(678) 636-9043", "(833) 300-6106", "(…
## $ distance <dbl> 366.2575, 20718.7077, 1238.2396, 1191.7090, 675.2866,…
## $ price <chr> NA, "$$", NA, "$$", "$$", NA, NA, "$$$", NA, "$", NA
categories, coordinates, transactions and location contain folded data frames.
# Flattening nested columns
# 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)
}
bikerent_flat <- bikerent_unique %>%
# 1. Flattening columns with data frame
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))
#Take a glimpse of the flatted data set
glimpse(bikerent_flat)
## Rows: 11
## Columns: 24
## $ id <chr> "JkkHRgYj0mvdgbMXFm436w", "FK7-M9BGyCgpEmVifc…
## $ alias <chr> "civil-bikes-atlanta", "aztec-cycles-stone-mo…
## $ name <chr> "Civil Bikes", "Aztec Cycles", "JUMP", "Atlan…
## $ image_url <chr> "https://s3-media4.fl.yelpcdn.com/bphoto/JqTL…
## $ is_closed <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FAL…
## $ url <chr> "https://www.yelp.com/biz/civil-bikes-atlanta…
## $ review_count <int> 11, 61, 1, 128, 103, 42, 15, 20, 1, 68, 12
## $ categories <chr> "Bike Rentals, Historical Tours", "Bikes, Bik…
## $ rating <dbl> 4.5, 5.0, 1.0, 4.5, 4.0, 4.5, 4.5, 4.5, 1.0, …
## $ transactions <chr> "", "", "", "", "", "", "", "", "", "", ""
## $ phone <chr> "+14043238754", "+16786369043", "+18333006106…
## $ display_phone <chr> "(404) 323-8754", "(678) 636-9043", "(833) 30…
## $ distance <dbl> 366.2575, 20718.7077, 1238.2396, 1191.7090, 6…
## $ price <chr> NA, "$$", NA, "$$", "$$", NA, NA, "$$$", NA, …
## $ coordinates.latitude <dbl> 33.74468, 33.80578, 33.74827, 33.75833, 33.76…
## $ coordinates.longitude <dbl> -84.37784, -84.17012, -84.39146, -84.36515, -…
## $ location.address1 <chr> "", "901 Main St", "", "151 Sampson St NE", "…
## $ location.address2 <chr> NA, "", "", "", "Ste E", NA, "Ste 101", "Ste …
## $ location.address3 <chr> "", "", NA, "", "", "", NA, "", "", NA, NA
## $ location.city <chr> "Atlanta", "Stone Mountain", "Atlanta", "Atla…
## $ location.zip_code <chr> "30312", "30083", "30301", "30312", "30307", …
## $ location.country <chr> "US", "US", "US", "US", "US", "US", "US", "US…
## $ location.state <chr> "GA", "GA", "GA", "GA", "GA", "GA", "GA", "GA…
## $ location.display_address <chr> "Atlanta, GA 30312", "901 Main St, Stone Moun…
# Check missing values in coordinates, "is_closed" and "distance"
bikerent_flat %>%
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
## 14 17 18 19
No missing data in coordinates, “is_closed” and “distance” variable.
# Delete responses outside of the tract boundary
bikerent_sf <- bikerent_flat %>%
st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"),
crs = 4326)
#View the geometries
tm_shape(bikerent_sf) +
tm_symbols(col = "review_count",
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=2.5,
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",
"Distance"="distance")) +
tm_shape(tract) + tm_borders() + tm_shape(atlanta) + tm_borders(col = 'darkred', lw=2)
## Legend for symbol sizes not available in view mode.
Some dots are falling outside of Atlanta city boundary.
# Delete rows that fall outside of the City of Atlanta boundary
#Set coordinate system
st_crs(atlanta) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
# sf subsets
bikerent_atl <- bikerent_sf[atlanta, ,op = st_intersects]
#View the filtered responses
tm_shape(bikerent_atl) +
tm_symbols(col = "review_count",
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=2.5,
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",
"Distance"="distance")) +
tm_shape(tract) + tm_borders() + tm_shape(atlanta) + tm_borders(col = 'darkred', lw=2)
## Legend for symbol sizes not available in view mode.
Find the right metrics: you may need to create new variables such as proportion, density, etc. Show at least one graph and at least one map with two variables that you are interested in examining (you can do more!). (Optional) you can calculate ‘distance to the nearest bike rental store’ for each Census Tract using sf::st_distance().
# After reading the data documentation, I realized that the data I requested from table B08006 and table B08301 are identical
# The data from table B08301 will be used for this question (columns havling prefix "commute")
# Calculate the cycling percentage
tract_q5 <- tract %>%
select(-c(trans.total,trans.bicycle)) %>%
mutate(bicycle.percent=commute.bicycle/commute.total)
# View Bike-Rental locations and the biking commute numbers on the same map
#View the filtered responses
tm_shape(tract_q5) +
tm_polygons(col = "commute.bicycle",
style="fixed", breaks=c(0, 1, 10, seq(30, 240, by=70)),
popup.vars = c("total commute"="commute.total",
"biking commute"="commute.bicycle")) +
tm_shape(bikerent_atl) +
tm_symbols(col = "review_count",
palette="Blues",
alpha = 0.6,
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=1.5,
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",
"Distance"="distance"))
## Legend for symbol sizes not available in view mode.
It seems like the tract with the highest number of biking-commuting does not have a biking rental store. And there are some tracts are far away from the current bke-rental place.
# View Bike-Rental locations and the biking percentages on the same map
#View the filtered responses
tm_shape(tract_q5) +
tm_polygons(col = "bicycle.percent",
# style="fixed", breaks=c(0, 1, 10, seq(30, 240, by=70)),
popup.vars = c("total commute"="commute.total",
"biking commute%"="bicycle.percent")) +
tm_shape(bikerent_atl) +
tm_symbols(col = "review_count",
palette="Blues",
alpha = 0.6,
size="rating",
style = "quantile",
sizes.legend=c(.5, 1,3)*1e6,
scale=1.5,
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",
"Distance"="distance"))
## Legend for symbol sizes not available in view mode.
The missing value on the map is due to commute.total=0
Based on the visual investigation, it seems like new bike rental places are needed at the mid-west of Atlanta.
# Calculate the ‘distance to the nearest bike rental store’ for Census Tract using sf::st_distance().
st_crs(tract_q5) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
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
# divide cycling numbers by the distance to the rental store
tract_q5$need.dist <- tract_q5$commute.bicycle / shortest_dist
# note that some need.dist will have some NA values because there are a few zeros in "shortest.m"
# replace those values with just the value of biking commute to show the biking conveniences in these tracts
tract_q5 <- tract_q5 %>%
mutate(need.dist = ifelse(is.na(need.dist), commute.bicycle, need.dist)) %>%
mutate(need.dist = ifelse(commute.bicycle==0, NA, need.dist))
# "NA" tracts with no biking commuting records by assuming that there won't be much profit earned if opening a new bike rental place there
tm_shape(tract_q5) +
tm_polygons(col = "need.dist",
# style="fixed", breaks=c(0, 1, 10, seq(30, 240, by=70)),
popup.vars = c("biking commute"="commute.bicycle",
"nearest bike rental(m)"="shortest.m"))
There are some tempting location choices for new bike rental stores around mid-west of Atlanta and the light-colored tract on the east can be a good choice if some other supporting evidences can be found. For examples, there are a good amount of recreational biking trips; the tract has good bike-lane conditions; etc.
# Plot shortest distance vs. number of biking commuting
library(ggplot2)
ggplot(tract_q5, aes(x=shortest.m, y=commute.bicycle)) +
geom_point() +
xlab("Shortest Distance to a Bike Rental Store(meter)") +
ylab("Number of Biking Commute in Each Tract")
It demonstrates that for the tracts having more nearby bike rental
store, they tend to have higher numbers of biking commuting on
average.
# # set coordinate system for spatial join
# atlcensus <- tract_q5 %>%
# st_sf(crs = 4326)
#
# # Spatial join
# # I want to visualize the polygon so I chose spatial join in the following order
# atlcensus_bikerent <- st_join(atlcensus, bikerent_atl, join = st_intersects)