Question 1. Choose two categories of businesses. See the Yelp API documentation if you need help with the choice.

# Reference: https://docs.developer.yelp.com/reference/v3_all_categories

library(httr)

url <- "https://api.yelp.com/v3/categories"

queryString <- list(locale = "en_US")

responseCat <- VERB("GET", url, query = queryString, add_headers('Authorization' = Sys.getenv("yelp_api")), content_type("application/octet-stream"), accept("application/json"))

# content(response, "text")
resultsCat <- content(responseCat)
# Reference: https://billpetti.github.io/2017-12-23-use-yelp-api-r-rstats/
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()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
yelp_httr_parse <- function(x) {

  parse_list <- list(title = x$title,
                     alias = x$alias,
                     parentCat = x$parent_aliases)
  
  parse_list <- lapply(parse_list, FUN = function(x) ifelse(is.null(x), "", x))
  
  df <- data_frame(title = parse_list$title,
                   alias = parse_list$alias, 
                   parentCat = parse_list$parentCat)
  df
}

resultsCat_list <- lapply(resultsCat$categories, FUN = yelp_httr_parse)
## Warning: `data_frame()` was deprecated in tibble 1.1.0.
## ℹ Please use `tibble()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
catload <- do.call("rbind", resultsCat_list)

Several categories were tried to request yelp API. It was funny that I always got tons of restaurant information back even when I chose “Boot Camps” under “Active Life”.

Since all the responses I got in my trials were rich in restaurants, “Italian” and “Chinese” under “Restaurant” are chosen for this assignment.

Question 2. Choose a county within the US. Use tidycensus package to download Census Tract polygons.

# The code chunks used for this questions are borrowed from the class material
# Reference: https://ujhwang.github.io/UrbanAnalytics2023/Lab/module_1/week1/Module1_Yelp_Census.html

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`.
# library(tidycensus)
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)
## 
## Attaching package: 'jsonlite'
## The following object is masked from 'package:purrr':
## 
##     flatten
# library(tidyverse)
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 = "PA",
          county = c("Forest"), 
          # The 3rd least populated county in Pennsylvania
          # https://worldpopulationreview.com/states/pennsylvania/counties
          variables = c(hhincome = 'B19019_001',
                        race.tot = "B02001_001", 
                        race.white = "B02001_002", 
                        race.black = 'B02001_003'
                        ),
          year = 2021,     # latest year of ACS data for Bucks, PA
          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%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |======================================================                |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
tract <- tract %>% 
  select(GEOID, 
         hhincome = hhincomeE, # New name = old name
         race.tot = race.totE,
         race.white = race.whiteE,
         race.black = race.blackE)
summary(tract)
##     GEOID              hhincome        race.tot      race.white  
##  Length:2           Min.   :41563   Min.   :2603   Min.   :2530  
##  Class :character   1st Qu.:42985   1st Qu.:3082   1st Qu.:2589  
##  Mode  :character   Median :44406   Median :3560   Median :2648  
##                     Mean   :44406   Mean   :3560   Mean   :2648  
##                     3rd Qu.:45828   3rd Qu.:4039   3rd Qu.:2706  
##                     Max.   :47250   Max.   :4518   Max.   :2765  
##    race.black              geometry
##  Min.   :   0.0   MULTIPOLYGON :2  
##  1st Qu.: 318.5   epsg:4269    :0  
##  Median : 637.0   +proj=long...:0  
##  Mean   : 637.0                    
##  3rd Qu.: 955.5                    
##  Max.   :1274.0
# View the Cencus Tract downloaded 
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tract) + tm_borders()

Only 2 polygons are showing on the map, which is good in terms of saving the limited daily API requests. However, a boring pattern of businesses distribution should be expected.

Question 3. Write R codes to get business data from Yelp using yelpr package for the selected county & business categories. Make sure you leave comments using hash tags (#) to explain what each code chunk is doing.

# Function: Get tract-wise radius
# Radius of each tract-polygon will be used as a specification for yelp API request later 
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
  # The centroid will be used as the longitude and latitude in yelp API request
  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.2 to make the circle a bit larger than the Census Tract.
  # Because - "The actual search radius may be lower than the suggested radius in   # dense urban areas, and higher in regions of less business density. 
  # https://docs.developer.yelp.com/reference/v3_all_categories"
  bb_center$radius <- r*1.2
  return(bb_center)
}
# Use "apply" function (lapply) 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])
# View the data prepared so far for yelp API request
tmap_mode('view')
## tmap mode set to interactive viewing
ready_4_yelp %>% 
  # 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) + tm_borders(col= 'blue')
# FUNCTION for API request
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)
  # Print required_n to detect -- 
  # API daily limits exhausted 
  # system variable changes not detected 
  # print(required_n)
  
  # 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_italy_list <- vector("list", nrow(ready_4_yelp))

# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
  yelp_italy_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "italian"))
  if (row %% 10 == 0){
    print(paste0("Current row: ", row))
  }
}

# Collapsing the list into a data.frame
yelp_italy <- yelp_italy_list %>% bind_rows() %>% as_tibble()

# print
yelp_italy %>% print(width=1000)
## # A tibble: 4 × 16
##   id                     alias                                  
##   <chr>                  <chr>                                  
## 1 fzd7AH-KbzT2JpqlRjsdGw bettinas-italian-restaurant-marienville
## 2 5VUhPDwQwuDQ-LmiP3fxlA tommys-italian-pizzeria-and-pub-sigel  
## 3 fzd7AH-KbzT2JpqlRjsdGw bettinas-italian-restaurant-marienville
## 4 B_CHbIyXankjUEt7gamshw roma-gardens-kane                      
##   name                         
##   <chr>                        
## 1 Bettina's Italian Restaurant 
## 2 Tommys Italian Pizzeria & Pub
## 3 Bettina's Italian Restaurant 
## 4 Roma Gardens                 
##   image_url                                                            is_closed
##   <chr>                                                                <lgl>    
## 1 https://s3-media4.fl.yelpcdn.com/bphoto/Gjv4AlZWvTfE61xllWO4JA/o.jpg FALSE    
## 2 https://s3-media3.fl.yelpcdn.com/bphoto/EdRkfLFBgSywPccBhp70WQ/o.jpg FALSE    
## 3 https://s3-media4.fl.yelpcdn.com/bphoto/Gjv4AlZWvTfE61xllWO4JA/o.jpg FALSE    
## 4 https://s3-media1.fl.yelpcdn.com/bphoto/rRYqchRJ8-PdNi1F0xd-_A/o.jpg FALSE    
##   url                                                                           
##   <chr>                                                                         
## 1 https://www.yelp.com/biz/bettinas-italian-restaurant-marienville?adjust_creat…
## 2 https://www.yelp.com/biz/tommys-italian-pizzeria-and-pub-sigel?adjust_creativ…
## 3 https://www.yelp.com/biz/bettinas-italian-restaurant-marienville?adjust_creat…
## 4 https://www.yelp.com/biz/roma-gardens-kane?adjust_creative=kptYkTFVgxlqfYNCmJ…
##   review_count categories   rating coordinates$latitude $longitude transactions
##          <int> <list>        <dbl>                <dbl>      <dbl> <list>      
## 1           13 <df [1 × 2]>    3.5                 41.5      -79.1 <list [0]>  
## 2           23 <df [3 × 2]>    4.5                 41.3      -79.1 <list [0]>  
## 3           13 <df [1 × 2]>    3.5                 41.5      -79.1 <list [0]>  
## 4            5 <df [1 × 2]>    3.5                 41.7      -78.8 <list [0]>  
##   price location$address1 $address2 $address3 $city       $zip_code $country
##   <chr> <chr>             <chr>     <chr>     <chr>       <chr>     <chr>   
## 1 $$    123 Chestnut St   ""        ""        Marienville 16239     US      
## 2 $     8476 Rt 949       ""        ""        Sigel       15860     US      
## 3 $$    123 Chestnut St   ""        ""        Marienville 16239     US      
## 4 $     1 Greeves St      ""        ""        Kane        16735     US      
##   $state $display_address phone        display_phone  distance
##   <chr>  <list>           <chr>        <chr>             <dbl>
## 1 PA     <chr [2]>        +18149277888 (814) 927-7888   20547.
## 2 PA     <chr [2]>        +18147522295 (814) 752-2295   22517.
## 3 PA     <chr [2]>        +18149277888 (814) 927-7888    3284.
## 4 PA     <chr [2]>        +18148379691 (814) 837-9691   30485.
# Repeat the process for a different category
# Prepare a collector
yelp_a_list <- vector("list", nrow(ready_4_yelp))

# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
  yelp_a_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "chinese"))
  if (row %% 10 == 0){
    print(paste0("Current row: ", row))
  }
}
# Collapsing the list into a data.frame
yelp_chinese <- yelp_a_list %>% bind_rows() %>% as_tibble()

# print
yelp_chinese %>% print(width=1000)
## # A tibble: 1 × 16
##   id                     alias           name      
##   <chr>                  <chr>           <chr>     
## 1 kB_soAAyST6qW09JqLNrhg peking-wok-kane Peking Wok
##   image_url                                                            is_closed
##   <chr>                                                                <lgl>    
## 1 https://s3-media1.fl.yelpcdn.com/bphoto/sjtmFff5FwntrPhh98xYOw/o.jpg FALSE    
##   url                                                                           
##   <chr>                                                                         
## 1 https://www.yelp.com/biz/peking-wok-kane?adjust_creative=kptYkTFVgxlqfYNCmJZ8…
##   review_count categories   rating coordinates$latitude $longitude transactions
##          <int> <list>        <dbl>                <dbl>      <dbl> <list>      
## 1            5 <df [1 × 2]>    4.5                 41.7      -78.8 <list [0]>  
##   price location$address1 $address2 $address3 $city $zip_code $country $state
##   <chr> <chr>             <chr>     <chr>     <chr> <chr>     <chr>    <chr> 
## 1 $$    79 N Fraley St    ""        ""        Kane  16735     US       PA    
##   $display_address phone        display_phone  distance
##   <list>           <chr>        <chr>             <dbl>
## 1 <chr [2]>        +18148371588 (814) 837-1588   30545.
yelp_italy <- yelp_italy %>% 
  mutate(cat="Italian")
yelp_chinese <- yelp_chinese %>% 
  mutate(cat="Chinese")
yelp_all <- bind_rows(yelp_italy,yelp_chinese)

Question 4. Map the locations of business using the downloaded data.

# Extract coordinates
yelp_sf <- 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
# Reference: https://rdocumentation.org/packages/tmap/versions/3.3-3/topics/tm_symbols
# library(leaflet)
# tmap_mode('view')

tm_shape(yelp_sf) +
  tm_dots(col = "cat",
             size="review_count",
             # 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"[[1]])) +
  tm_shape(tract) + tm_borders()
## Legend for symbol sizes not available in view mode.

Question 5. Answer the following questions:

What’s the county and state of your choice? Forest County in Pennsylvania.

How many businesses are there in total?

cat("There are", nrow(distinct(yelp_all)), "Italian and Chinese restaurants in total." )
## There are 5 Italian and Chinese restaurants in total.

However, based on the map drawn in Question 4, there is really only 1 Italian restaurant falling in the boundary.

How many businesses are there for each business category?

cat( nrow(distinct(yelp_italy)), "Italian restaurants and", nrow(distinct(yelp_chinese)), "Chinese restaurants.")
## 4 Italian restaurants and 1 Chinese restaurants.

But again, the results are simply showing the responses from the yelp api requests. Based on the map, there is only 1 Italian restaurant and no Chinese restaurant.

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)? Since there is only one dot appeared around middle of this county, there is no obvious pattern of the businesses (Italian & Chinese Restaurant) chosen for this county.

(Optional) Are there any other interesting findings? It seems like the Italian restaurant located in the south but outside of the county is more popular than the one within the county. But those reviews could be contributed by people living in its neighbor-county.