tidycensus::census_api_key(Sys.getenv("census_api"))
library(tidycensus)
library(sf)
library(tmap)
library(jsonlite)
library(tidyverse)
library(httr)
library(jsonlite)
library(reshape2)
library(here)
library(yelpr)
library(knitr)
library(tigris)
library(skimr)
FD_tract <- suppressMessages(
get_acs(geography = "tract",
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.car = "B08006_002",
trans.drovealone = "B08006_003",
trans.carpooled = "B08006_004", # Notice that I was not interested in 005-007 (2 person/ 4 person carpool etc.)
trans.pubtrans = "B08006_008", # Did not want to download any details about the type of public transport (009-0013)
trans.bicycle = "B08006_014",
trans.walk = "B08006_015",
trans.WfH = "B08006_017",
med_housexp = "B25104_001",
med_realestate_taxes = "B25103_001"
),
year = 2020,
survey = "acs5", # American Community Survey 5-year estimate
geometry = TRUE, # returns sf objects
output = "wide") # wide vs. long
)
FD_tract <- FD_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.car = trans.carE,
trans.drovealone = trans.drovealoneE,
trans.carpooled = trans.carpooledE,
trans.pubtrans = trans.pubtransE,
trans.bicycle = trans.bicycleE,
trans.walk = trans.walkE,
trans.WfH = trans.WfHE,
Med_HHExp = med_housexpE,
med_RETaxes = med_realestate_taxesE)
atlanta <- places('GA')%>%
filter(NAME == 'Atlanta')
FD_atl <- FD_tract[atlanta, ,op = st_intersects]
# 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)
}
# Using a functional
# We use a functional (sapply) to apply this custom function to each Census Tract.
epsg_id <- 4326
r4all_apply <- FD_atl %>%
st_geometry() %>%
st_transform(crs = epsg_id) %>%
lapply(., function(x) get_r(x, epsg_id = epsg_id))
r4all_apply <- bind_rows(r4all_apply)
# Appending X Y coordinates as separate columns
ready_4_yelp <- r4all_apply %>%
mutate(x = st_coordinates(.)[,1],
y = st_coordinates(.)[,2])
tmap_mode('view')
# Select the first 10 rows
ready_4_yelp[1:10,] %>%
# Draw a buffer centered at the centroid of Tract polygons.
# Radius of the buffer is the radius we just calculated using loop
st_buffer(., dist = .$radius) %>%
# Display this buffer in red
tm_shape(.) + tm_polygons(alpha = 0.5, col = 'red') +
# Display the original polygon in blue
tm_shape(FD_atl[1:10,]) + tm_borders(col= 'blue')
# 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("yelp_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("yelp_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_bikerentals_list <- vector("list", nrow(ready_4_yelp))
# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
yelp_bikerentals_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_bikerentals <- yelp_bikerentals_list %>% bind_rows() %>% as_tibble()
# print
yelp_bikerentals %>% print(width=1000)
# Save Yelp data
saveRDS(yelp_bikerentals, "bikerentals.rds")
# Extract coordinates and convert to sf
yelp_bikerentals <- readRDS("bikerentals.rds")
yelp_sf_bikerentals <- yelp_bikerentals %>%
mutate(x = .$coordinates$longitude,
y = .$coordinates$latitude) %>%
filter(!is.na(x) & !is.na(y)) %>%
st_as_sf(coords = c("x", "y"), crs = 4326)
# Map
tm_shape(FD_atl) + tm_borders()+
tm_shape(yelp_sf_bikerentals) +
tm_dots(col = "review_count", style="quantile")
yelp_bikerentals <- readRDS("bikerentals.rds")
yelp_dup <- yelp_bikerentals[!duplicated(yelp_bikerentals$id),]
# Flatten the data frame within coordinates and location columns
yelp_flat <- yelp_dup %>%
jsonlite::flatten() %>%
as_tibble()
# Concatenate what's inside the list-columns (transaction and
# location.display_address)
yelp_concat <- yelp_flat %>%
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=", ")))
# 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)
}
yelp_flat2 <- yelp_concat %>%
mutate(categories = categories %>% map_chr(concate_list))
yelp_flat2 %>% print(width = 1000)
## # A tibble: 10 × 24
## id alias
## <chr> <chr>
## 1 tMNV5bj4rqud0cRRQiPbWA outback-bikes-atlanta
## 2 rbf8bVY0cuqyGZtbn691lg pedego-electric-bikes-atlanta-atlanta-2
## 3 BozJwfoXvoDEUj-sgr7WDg podium-multisport-atlanta
## 4 JkkHRgYj0mvdgbMXFm436w civil-bikes-atlanta
## 5 FK7-M9BGyCgpEmVifcPfoA aztec-cycles-stone-mountain
## 6 UmftRC3h0h_owHEm5ZLp7Q jump-atlanta-2
## 7 b3nacMG8PR77GNCaI4RBKA atlanta-bicycle-barn-atlanta
## 8 gcl6O-ZWTTra5ljEics_gw cloud-of-goods-atlanta-atlanta-2
## 9 8PfRbXo6qhKliGDCp5l79g atlanta-pro-bikes-atlanta
## 10 vfp82FZBVz1Hcg6FwTjWcg relay-bike-share-atlanta
## name
## <chr>
## 1 Outback Bikes
## 2 Pedego Electric Bikes Atlanta
## 3 Podium Multisport
## 4 Civil Bikes
## 5 Aztec Cycles
## 6 JUMP
## 7 Atlanta Bicycle Barn
## 8 Cloud of Goods - Atlanta
## 9 Atlanta Pro Bikes
## 10 Relay Bike Share
## image_url
## <chr>
## 1 https://s3-media4.fl.yelpcdn.com/bphoto/rnpOTcs3WwjTq1JsfV1b8w/o.jpg
## 2 https://s3-media2.fl.yelpcdn.com/bphoto/Z7KlxC0vcyoxOCSxbH3Rrg/o.jpg
## 3 https://s3-media1.fl.yelpcdn.com/bphoto/T78pUkBulcQ5osv4mVGTiQ/o.jpg
## 4 https://s3-media4.fl.yelpcdn.com/bphoto/JqTLT-chrqtbyuoB-52gdw/o.jpg
## 5 https://s3-media3.fl.yelpcdn.com/bphoto/-UkKevNihxQhIgFi_zR2iw/o.jpg
## 6 https://s3-media2.fl.yelpcdn.com/bphoto/D87H00XdLWZJS-LvQkTalA/o.jpg
## 7 https://s3-media3.fl.yelpcdn.com/bphoto/Ik2pMce41_MRcg3svjTbSQ/o.jpg
## 8 https://s3-media4.fl.yelpcdn.com/bphoto/88hjMKknmHDpv3970N_-Wg/o.jpg
## 9 https://s3-media1.fl.yelpcdn.com/bphoto/1s0fhhJvN3z-SUPizRy5sw/o.jpg
## 10 https://s3-media1.fl.yelpcdn.com/bphoto/kOYlKAb5ZeQehYcz0ucnVQ/o.jpg
## is_closed
## <lgl>
## 1 FALSE
## 2 FALSE
## 3 FALSE
## 4 FALSE
## 5 FALSE
## 6 FALSE
## 7 FALSE
## 8 FALSE
## 9 FALSE
## 10 FALSE
## url
## <chr>
## 1 https://www.yelp.com/biz/outback-bikes-atlanta?adjust_creative=RVjHz4PIp9hJE…
## 2 https://www.yelp.com/biz/pedego-electric-bikes-atlanta-atlanta-2?adjust_crea…
## 3 https://www.yelp.com/biz/podium-multisport-atlanta?adjust_creative=RVjHz4PIp…
## 4 https://www.yelp.com/biz/civil-bikes-atlanta?adjust_creative=RVjHz4PIp9hJEoX…
## 5 https://www.yelp.com/biz/aztec-cycles-stone-mountain?adjust_creative=RVjHz4P…
## 6 https://www.yelp.com/biz/jump-atlanta-2?adjust_creative=RVjHz4PIp9hJEoXgmBr1…
## 7 https://www.yelp.com/biz/atlanta-bicycle-barn-atlanta?adjust_creative=RVjHz4…
## 8 https://www.yelp.com/biz/cloud-of-goods-atlanta-atlanta-2?adjust_creative=RV…
## 9 https://www.yelp.com/biz/atlanta-pro-bikes-atlanta?adjust_creative=RVjHz4PIp…
## 10 https://www.yelp.com/biz/relay-bike-share-atlanta?adjust_creative=RVjHz4PIp9…
## review_count categories rating
## <int> <chr> <dbl>
## 1 103 Bikes, Bike Repair/Maintenance, Bike Rentals 4
## 2 15 Bikes, Bike Rentals, Bike Repair/Maintenance 4.5
## 3 20 Bikes, Bike Rentals 4.5
## 4 11 Bike Rentals, Historical Tours 4.5
## 5 61 Bikes, Bike Repair/Maintenance, Bike Rentals 5
## 6 1 Scooter Rentals, Bike Rentals 1
## 7 128 Bike Rentals, Bike Repair/Maintenance, Bikes 4.5
## 8 1 Scooter Rentals, Baby Gear & Furniture, Bike Rentals 1
## 9 42 Bike Repair/Maintenance, Bikes, Bike Rentals 4.5
## 10 12 Party Bike Rentals, Bike Rentals, Bike Sharing 2
## transactions price phone display_phone distance coordinates.latitude
## <chr> <chr> <chr> <chr> <dbl> <dbl>
## 1 "" $$ +14046884878 (404) 688-4878 6295. 33.8
## 2 "" <NA> +14049753915 (404) 975-3915 8604. 33.7
## 3 "" $$$ +14048923400 (404) 892-3400 781. 33.8
## 4 "" <NA> +14043238754 (404) 323-8754 366. 33.7
## 5 "" $$ +16786369043 (678) 636-9043 20719. 33.8
## 6 "" <NA> +18333006106 (833) 300-6106 1238. 33.7
## 7 "" $$ +17708732413 (770) 873-2413 274. 33.8
## 8 "" <NA> +14075453103 (407) 545-3103 432. 33.8
## 9 "" <NA> +14042541230 (404) 254-1230 450. 33.8
## 10 "" <NA> +16787109900 (678) 710-9900 2307. 33.6
## coordinates.longitude location.address1 location.address2
## <dbl> <chr> <chr>
## 1 -84.3 "484 Moreland Ave NE" "Ste E"
## 2 -84.4 "414 Bill Kennedy Way" "Ste 101"
## 3 -84.3 "1167 Zonolite Pl NE" "Ste A2"
## 4 -84.4 "" <NA>
## 5 -84.2 "901 Main St" ""
## 6 -84.4 "" ""
## 7 -84.4 "151 Sampson St NE" ""
## 8 -84.4 <NA> <NA>
## 9 -84.4 "1039 N Highland Ave NE" <NA>
## 10 -84.5 "" ""
## location.address3 location.city location.zip_code location.country
## <chr> <chr> <chr> <chr>
## 1 "" Atlanta 30307 US
## 2 <NA> Atlanta 30316 US
## 3 "" Atlanta 30306 US
## 4 "" Atlanta 30312 US
## 5 "" Stone Mountain 30083 US
## 6 <NA> Atlanta 30301 US
## 7 "" Atlanta 30312 US
## 8 "" Atlanta 30303 US
## 9 "" Atlanta 30306 US
## 10 <NA> Atlanta 30349 US
## location.state location.display_address
## <chr> <chr>
## 1 GA 484 Moreland Ave NE, Ste E, Atlanta, GA 30307
## 2 GA 414 Bill Kennedy Way, Ste 101, Atlanta, GA 30316
## 3 GA 1167 Zonolite Pl NE, Ste A2, Atlanta, GA 30306
## 4 GA Atlanta, GA 30312
## 5 GA 901 Main St, Stone Mountain, GA 30083
## 6 GA Atlanta, GA 30301
## 7 GA 151 Sampson St NE, Atlanta, GA 30312
## 8 GA Atlanta, GA 30303
## 9 GA 1039 N Highland Ave NE, Atlanta, GA 30306
## 10 GA Atlanta, GA 30349
# Identify whether there exists any NA values.
yelp_flat2 %>%
map_dbl(., function(x) sum(is.na(x)))
## id alias name
## 0 0 0
## image_url is_closed url
## 0 0 0
## review_count categories rating
## 0 0 0
## transactions price phone
## 0 6 0
## display_phone distance coordinates.latitude
## 0 0 0
## coordinates.longitude location.address1 location.address2
## 0 1 3
## location.address3 location.city location.zip_code
## 3 0 0
## location.country location.state location.display_address
## 0 0 0
# No NA in coordinate columns
# Converting yelp_flat2 into a sf object
yelp_sf <- yelp_flat2 %>%
st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"), crs = 4326)
# Make sure two layers have same crs
atlanta <- st_transform(atlanta, crs = st_crs(yelp_sf))
# Delete points outside boundary
yelp_in <- yelp_sf[atlanta, ,op = st_intersects]
# Make sure two layers have same crs
FD_atl <- st_transform(FD_atl, crs = st_crs(yelp_in))
# Join tract geometry with the number of bike rentals in tract
bike_in_tract <- st_join(FD_atl, yelp_in %>% mutate(count = 1)) %>%
group_by(GEOID) %>%
summarise(count = sum(count, na.rm = T))
# join back the counts of bike rentals to the Tract data
FD_bike <- FD_atl %>%
left_join(bike_in_tract %>% st_set_geometry(NULL), by = "GEOID")
FD_bike$bikepercent <- (FD_bike$trans.bicycle/FD_bike$trans.total)*100
FD_bike$carpercent <- (FD_bike$trans.car/FD_bike$trans.total)*100
Only 8 tracts have bike rentals
tm_shape(FD_bike) + tm_polygons(col = "count") +tm_shape(yelp_in) +tm_dots()
Tracts that have bike rentals presence have higher percentage of bike commuters on average.
boxplot(bikepercent~count, data=FD_bike, main="Boxplot of bike rentals by bike commuters", xlab="Whether bike rentals are present", ylab="Percentage of bike commuters")
Tracts that have bike rentals presence have lower percentage of car commuters on average.
boxplot(carpercent~count, data=FD_bike, main="Boxplot of bike rentals by car commuters", xlab="Whether bike rentals are present", ylab="Percentage of car commuters")
binary1 <- glm(count~bikepercent, family=binomial, data=FD_bike)
summary(binary1)
##
## Call:
## glm(formula = count ~ bikepercent, family = binomial, data = FD_bike)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.4998 0.4399 -7.956 1.78e-15 ***
## bikepercent 0.1139 0.1565 0.728 0.467
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 61.448 on 210 degrees of freedom
## Residual deviance: 61.022 on 209 degrees of freedom
## (因为不存在,3个观察量被删除了)
## AIC: 65.022
##
## Number of Fisher Scoring iterations: 6
binary2 <- glm(count~carpercent, family=binomial, data=FD_bike)
summary(binary2)
##
## Call:
## glm(formula = count ~ carpercent, family = binomial, data = FD_bike)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -2.01011 1.66345 -1.208 0.227
## carpercent -0.02024 0.02481 -0.816 0.415
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 61.448 on 210 degrees of freedom
## Residual deviance: 60.826 on 209 degrees of freedom
## (因为不存在,3个观察量被删除了)
## AIC: 64.826
##
## Number of Fisher Scoring iterations: 6