tidycensus::census_api_key(Sys.getenv("census_api"))
## To install your API key for use in future sessions, run this function with `install = TRUE`.
library(tidycensus)
library(sf)
library(tmap)
library(jsonlite)
library(tidyverse)
library(httr)
library(jsonlite)
library(reshape2)
library(here)
library(yelpr)
library(knitr)
library(tigris)
#### Tract polygons for the Yelp query
tract <- suppressMessages(
get_acs(geography = "tract", # or "block group", "county", "state" etc.
state = "GA",
county = c("Clayton"),
variables = c(hhincome = 'B19019_001'),
year = 2019,
survey = "acs5", # American Community Survey 5-year estimate
geometry = TRUE, # returns sf objects
output = "wide") # wide vs. long
)
# Retaining only those I want.
# Notice that select function can also change names when it selects columns.
tract <- tract %>%
select(GEOID,
hhincome = hhincomeE, # New name = old name
)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tract) + tm_borders()
# 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 <- tract %>%
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')
## tmap mode set to interactive viewing
# 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(tract[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_chinese_list <- vector("list", nrow(ready_4_yelp))
# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
yelp_chinese_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "chinese"))
if (row %% 10 == 0){
print(paste0("Current row: ", row))
}
}
## [1] "Current row: 10"
## [1] "Current row: 20"
## [1] "Current row: 30"
## [1] "Current row: 40"
## [1] "Current row: 50"
# Collapsing the list into a data.frame
yelp_chinese <- yelp_chinese_list %>% bind_rows() %>% as_tibble()
# print
yelp_chinese %>% print(width=1000)
## # A tibble: 252 × 16
## id alias
## <chr> <chr>
## 1 4ZEwrqwOqjN2ojhqjztwag china-wang-riverdale
## 2 -v9c3IDIM3zOFBFgS_lEug panda-express-riverdale
## 3 O9cTMfMMcT1UtTA3w5Nh1w great-china-riverdale
## 4 H80S-Hl7v-labthz4B-TcA hong-kong-city-restaurant-riverdale
## 5 X5KBjCijxjcJYpARnz2f-A golden-gate-chinese-restaurant-forest-park
## 6 zLhpZ7ljsIi2U8LoMjCfyA wong-wong-bbq-lake-city
## 7 adHaO4Se7glFvHnd-w9nKw new-china-cafeteria-forest-park
## 8 xj20tspcCMOKRLqXPoN_Vg panda-express-atlanta-17
## 9 ElEVYsa2xGpxUCMOfRv59Q new-china-wings-morrow
## 10 3GLb7ajNoV4b2f6M6N8MYg hong-kong-express-forest-park-2
## name
## <chr>
## 1 China Wang
## 2 Panda Express
## 3 Great China
## 4 Hong Kong City Restaurant
## 5 Golden Gate Chinese Restaurant
## 6 Wong Wong BBQ
## 7 New China Cafeteria
## 8 Panda Express
## 9 New China Wings
## 10 Hong Kong Express
## image_url
## <chr>
## 1 "https://s3-media1.fl.yelpcdn.com/bphoto/bV3qFHt7MI3J8R43ytRH-A/o.jpg"
## 2 "https://s3-media2.fl.yelpcdn.com/bphoto/MLJSPqbNecoEAuno2_P61A/o.jpg"
## 3 "https://s3-media2.fl.yelpcdn.com/bphoto/b6LKNq7yGoq6ft6IGjtx1w/o.jpg"
## 4 ""
## 5 "https://s3-media2.fl.yelpcdn.com/bphoto/ObaOXMb77RlX3V-_XxXzkw/o.jpg"
## 6 "https://s3-media2.fl.yelpcdn.com/bphoto/fBqDOEQayv7tJIiMUVJb2Q/o.jpg"
## 7 "https://s3-media2.fl.yelpcdn.com/bphoto/PXY_H_56EYisEj1pPimUkg/o.jpg"
## 8 "https://s3-media3.fl.yelpcdn.com/bphoto/SNG8Xmx8Cc8rEgMtxDYcXQ/o.jpg"
## 9 "https://s3-media2.fl.yelpcdn.com/bphoto/XnFq56PskPcFAGmZzWSmcg/o.jpg"
## 10 "https://s3-media3.fl.yelpcdn.com/bphoto/TZdfzy8_910zyDYLQaumfA/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/china-wang-riverdale?adjust_creative=RVjHz4PIp9hJEo…
## 2 https://www.yelp.com/biz/panda-express-riverdale?adjust_creative=RVjHz4PIp9h…
## 3 https://www.yelp.com/biz/great-china-riverdale?adjust_creative=RVjHz4PIp9hJE…
## 4 https://www.yelp.com/biz/hong-kong-city-restaurant-riverdale?adjust_creative…
## 5 https://www.yelp.com/biz/golden-gate-chinese-restaurant-forest-park?adjust_c…
## 6 https://www.yelp.com/biz/wong-wong-bbq-lake-city?adjust_creative=RVjHz4PIp9h…
## 7 https://www.yelp.com/biz/new-china-cafeteria-forest-park?adjust_creative=RVj…
## 8 https://www.yelp.com/biz/panda-express-atlanta-17?adjust_creative=RVjHz4PIp9…
## 9 https://www.yelp.com/biz/new-china-wings-morrow?adjust_creative=RVjHz4PIp9hJ…
## 10 https://www.yelp.com/biz/hong-kong-express-forest-park-2?adjust_creative=RVj…
## review_count categories rating coordinates$latitude $longitude transactions
## <int> <list> <dbl> <dbl> <dbl> <list>
## 1 17 <df [2 × 2]> 4 33.6 -84.4 <chr [2]>
## 2 29 <df [2 × 2]> 3.5 33.6 -84.4 <chr [2]>
## 3 19 <df [1 × 2]> 3.5 33.5 -84.4 <chr [1]>
## 4 1 <df [1 × 2]> 5 33.6 -84.4 <chr [0]>
## 5 88 <df [1 × 2]> 3.5 33.6 -84.4 <chr [1]>
## 6 10 <df [1 × 2]> 4.5 33.6 -84.3 <chr [1]>
## 7 12 <df [1 × 2]> 4 33.6 -84.4 <chr [1]>
## 8 60 <df [2 × 2]> 2.5 33.6 -84.4 <chr [2]>
## 9 13 <df [2 × 2]> 3.5 33.6 -84.4 <chr [1]>
## 10 5 <df [1 × 2]> 4 33.6 -84.4 <chr [0]>
## price location$address1 $address2 $address3 $city $zip_code $country
## <chr> <chr> <chr> <chr> <chr> <chr> <chr>
## 1 $ 7020 Hwy 85 <NA> <NA> Riverdale 30274 US
## 2 $$ 7105 Highway 85 <NA> <NA> Riverdale 30274 US
## 3 $ 7565 Hwy 85 "" "" Riverdale 30274 US
## 4 <NA> 6910 Hwy 85 "" "" Riverdale 30274 US
## 5 $$ 4353 Jonesboro Rd "" "" Forest Park 30297 US
## 6 <NA> 5208 Jonesboro Rd "" <NA> Lake City 30260 US
## 7 $ 4873 Jonesboro Rd "" "" Forest Park 30297 US
## 8 $ 12700 Spine Road Sw "#E-F4" "" Atlanta 30354 US
## 9 $ 1174 Forest Pkwy "" "" Morrow 30260 US
## 10 <NA> 4568 Old Dixie Hwy "Ste 4" <NA> Forest Park 30297 US
## $state $display_address phone display_phone distance
## <chr> <list> <chr> <chr> <dbl>
## 1 GA <chr [2]> "+17709071881" "(770) 907-1881" 603.
## 2 GA <chr [2]> "+17709070816" "(770) 907-0816" 613.
## 3 GA <chr [2]> "+17709916789" "(770) 991-6789" 1408.
## 4 GA <chr [2]> "+17709913885" "(770) 991-3885" 893.
## 5 GA <chr [2]> "+14043667600" "(404) 366-7600" 1279.
## 6 GA <chr [2]> "+16786083857" "(678) 608-3857" 3344.
## 7 GA <chr [2]> "" "" 2311.
## 8 GA <chr [3]> "+14043050891" "(404) 305-0891" 1853.
## 9 GA <chr [2]> "+14046080058" "(404) 608-0058" 2912.
## 10 GA <chr [3]> "+14704283297" "(470) 428-3297" 1192.
## # ℹ 242 more rows
# Extract coordinates
yelp_sf_chi <- yelp_chinese %>%
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(tract) + tm_borders()+
tm_shape(yelp_sf_chi) +
tm_dots(col = "review_count", style="quantile")
# Prepare a collector
yelp_cafe_list <- vector("list", nrow(ready_4_yelp))
# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
yelp_cafe_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "cafes"))
if (row %% 10 == 0){
print(paste0("Current row: ", row))
}
}
## [1] "Current row: 10"
## [1] "Current row: 20"
## [1] "Current row: 30"
## [1] "Current row: 40"
## [1] "Current row: 50"
# Collapsing the list into a data.frame
yelp_cafe <- yelp_cafe_list %>% bind_rows() %>% as_tibble()
# print
yelp_cafe %>% print(width=1000)
## # A tibble: 80 × 16
## id alias
## <chr> <chr>
## 1 cp3vImW5gM5QvXJv2L83-Q cafe-hot-wing-jonesboro
## 2 Z7Xc-sFFczx2BQunHAyMwA yummies-cafe-riverdale
## 3 b5i9wWKvOfrJ9nh9ni63AQ kennys-cafe-forest-park
## 4 wnP0du8lZ7zn4tL9OJJCbA msight-tv-studio-cafe-jonesboro-2
## 5 Z7Xc-sFFczx2BQunHAyMwA yummies-cafe-riverdale
## 6 TkC7CRAUgMeZIBzT_crFyA t-bird-cafe-morrow
## 7 wnP0du8lZ7zn4tL9OJJCbA msight-tv-studio-cafe-jonesboro-2
## 8 wnP0du8lZ7zn4tL9OJJCbA msight-tv-studio-cafe-jonesboro-2
## 9 b5i9wWKvOfrJ9nh9ni63AQ kennys-cafe-forest-park
## 10 GMKjG2IL0swWR7_MNk9Bjg fresh-healthy-cafe-atlanta
## name
## <chr>
## 1 Cafe Hot Wing
## 2 Yummies Cafe
## 3 Kenny's Cafe
## 4 Msight TV Studio Cafe
## 5 Yummies Cafe
## 6 T-Bird Cafe
## 7 Msight TV Studio Cafe
## 8 Msight TV Studio Cafe
## 9 Kenny's Cafe
## 10 Fresh Healthy Cafe
## image_url
## <chr>
## 1 https://s3-media2.fl.yelpcdn.com/bphoto/Yh_dSjap_Yo2z89x_AMWWg/o.jpg
## 2 https://s3-media3.fl.yelpcdn.com/bphoto/AFRiF7scpJXjo44toFODEQ/o.jpg
## 3 https://s3-media2.fl.yelpcdn.com/bphoto/2Ka_GSSOz9IXl3cfdum3pQ/o.jpg
## 4 https://s3-media3.fl.yelpcdn.com/bphoto/IJD1-GbQCjiZtn1oA3S-4g/o.jpg
## 5 https://s3-media3.fl.yelpcdn.com/bphoto/AFRiF7scpJXjo44toFODEQ/o.jpg
## 6 https://s3-media2.fl.yelpcdn.com/bphoto/XfUHP8eWDcgGDBP2Ao2pwQ/o.jpg
## 7 https://s3-media3.fl.yelpcdn.com/bphoto/IJD1-GbQCjiZtn1oA3S-4g/o.jpg
## 8 https://s3-media3.fl.yelpcdn.com/bphoto/IJD1-GbQCjiZtn1oA3S-4g/o.jpg
## 9 https://s3-media2.fl.yelpcdn.com/bphoto/2Ka_GSSOz9IXl3cfdum3pQ/o.jpg
## 10 https://s3-media2.fl.yelpcdn.com/bphoto/Z7CV3wr43KPHK1ppdEAP6Q/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/cafe-hot-wing-jonesboro?adjust_creative=RVjHz4PIp9h…
## 2 https://www.yelp.com/biz/yummies-cafe-riverdale?adjust_creative=RVjHz4PIp9hJ…
## 3 https://www.yelp.com/biz/kennys-cafe-forest-park?adjust_creative=RVjHz4PIp9h…
## 4 https://www.yelp.com/biz/msight-tv-studio-cafe-jonesboro-2?adjust_creative=R…
## 5 https://www.yelp.com/biz/yummies-cafe-riverdale?adjust_creative=RVjHz4PIp9hJ…
## 6 https://www.yelp.com/biz/t-bird-cafe-morrow?adjust_creative=RVjHz4PIp9hJEoXg…
## 7 https://www.yelp.com/biz/msight-tv-studio-cafe-jonesboro-2?adjust_creative=R…
## 8 https://www.yelp.com/biz/msight-tv-studio-cafe-jonesboro-2?adjust_creative=R…
## 9 https://www.yelp.com/biz/kennys-cafe-forest-park?adjust_creative=RVjHz4PIp9h…
## 10 https://www.yelp.com/biz/fresh-healthy-cafe-atlanta?adjust_creative=RVjHz4PI…
## review_count categories rating coordinates$latitude $longitude transactions
## <int> <list> <dbl> <dbl> <dbl> <list>
## 1 27 <df [1 × 2]> 3 33.6 -84.4 <chr [2]>
## 2 78 <df [3 × 2]> 4.5 33.5 -84.4 <chr [2]>
## 3 18 <df [2 × 2]> 4.5 33.6 -84.4 <chr [2]>
## 4 1 <df [2 × 2]> 1 33.5 -84.4 <list [0]>
## 5 78 <df [3 × 2]> 4.5 33.5 -84.4 <chr [2]>
## 6 2 <df [3 × 2]> 5 33.6 -84.3 <list [0]>
## 7 1 <df [2 × 2]> 1 33.5 -84.4 <list [0]>
## 8 1 <df [2 × 2]> 1 33.5 -84.4 <list [0]>
## 9 18 <df [2 × 2]> 4.5 33.6 -84.4 <chr [2]>
## 10 103 <df [2 × 2]> 3.5 33.6 -84.4 <chr [0]>
## price location$address1 $address2 $address3 $city
## <chr> <chr> <chr> <chr> <chr>
## 1 $ "6595 Tara Blvd" "" "" Jonesboro
## 2 <NA> "7523 Highway 85" "" <NA> Riverdale
## 3 $ "4542 Old Dixie Hwy" "" <NA> Forest Park
## 4 <NA> "" <NA> <NA> Jonesboro
## 5 <NA> "7523 Highway 85" "" <NA> Riverdale
## 6 <NA> "6790 Mt Zion Blvd" "" <NA> Morrow
## 7 <NA> "" <NA> <NA> Jonesboro
## 8 <NA> "" <NA> <NA> Jonesboro
## 9 $ "4542 Old Dixie Hwy" "" <NA> Forest Park
## 10 $ "6000 N Terminal Pkwy" "Terminal C, Gate C 45" "" Atlanta
## $zip_code $country $state $display_address phone display_phone
## <chr> <chr> <chr> <list> <chr> <chr>
## 1 30236 US GA <chr [2]> "+17704713200" "(770) 471-3200"
## 2 30274 US GA <chr [2]> "+16785452849" "(678) 545-2849"
## 3 30297 US GA <chr [2]> "+14049689185" "(404) 968-9185"
## 4 30236 US GA <chr [1]> "+16785323622" "(678) 532-3622"
## 5 30274 US GA <chr [2]> "+16785452849" "(678) 545-2849"
## 6 30260 US GA <chr [2]> "" ""
## 7 30236 US GA <chr [1]> "+16785323622" "(678) 532-3622"
## 8 30236 US GA <chr [1]> "+16785323622" "(678) 532-3622"
## 9 30297 US GA <chr [2]> "+14049689185" "(404) 968-9185"
## 10 30320 US GA <chr [3]> "+14042090907" "(404) 209-0907"
## distance
## <dbl>
## 1 980.
## 2 1295.
## 3 1199.
## 4 3142.
## 5 2649.
## 6 2556.
## 7 838.
## 8 3439.
## 9 3450.
## 10 4095.
## # ℹ 70 more rows
# Extract coordinates
yelp_sf_cafe <- yelp_cafe %>%
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(tract) + tm_borders()+
tm_shape(yelp_sf_cafe) +
tm_dots(col = "review_count", style="quantile")
yelp_all <- bind_rows(yelp_cafe,yelp_chinese)
# Extract coordinates
yelp_sf_all <- yelp_all %>%
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(tract) + tm_borders()+
tm_shape(yelp_sf_all) +
tm_dots(col = "review_count", style="quantile")
Q1: What’s the county and state of your choice? Clayton county, GA
Q2: How many businesses are there in total? 332 in total
Q3: How many businesses are there for each business category? Chinese restaurants:252 Cafes:80
Q4: Upon visual inspection, can you see any noticeable spatial patterns to the way they are distributed across the county (e.g., clustering of businesses at some parts of the county)? Most of the businesses located at the north part of the county especially at the northwest corner where is the Hartsfield-Jackson Airport.