Question 1. Prepare the yelp data you downloaded for Mini-Assignment 1

Since the yelp data used in mini assignment was too boring to tidy, a different set of data (Mediterranean restaurants in Pittsburgh area, which is one of my original choice for mini assignment 1) will be used instead.

Only one category will be used for yelp API request to save its daily usage limits.

#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(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)
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 = "PA",
          county = c("allegheny"), 
          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
)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
pittsburgh <- places('PA') %>%
  filter(NAME == 'Pittsburgh')
## Retrieving data for the year 2021
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%
tract <- tract[pittsburgh,]
#View the geographic boundary
tract <- 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(tract) + tm_borders() + tm_shape(pittsburgh) + tm_borders(col = 'darkred')
#Take an overall glimpse of the census data
summary(tract)
##     GEOID              hhincome         race.tot      race.white  
##  Length:180         Min.   : 12130   Min.   :   0   Min.   :   0  
##  Class :character   1st Qu.: 41072   1st Qu.:1911   1st Qu.:1036  
##  Mode  :character   Median : 56790   Median :2508   Median :1748  
##                     Mean   : 59807   Mean   :2652   Mean   :1872  
##                     3rd Qu.: 69651   3rd Qu.:3372   3rd Qu.:2621  
##                     Max.   :247930   Max.   :7282   Max.   :6167  
##                     NA's   :14                                    
##    race.black               geometry  
##  Min.   :   0.00   MULTIPOLYGON :180  
##  1st Qu.:  68.75   epsg:4269    :  0  
##  Median : 266.00   +proj=long...:  0  
##  Mean   : 495.19                      
##  3rd Qu.: 690.50                      
##  Max.   :2948.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: 9 × 6
##   GEOID       hhincome race.tot race.white race.black                   geometry
##   <chr>          <dbl>    <dbl>      <dbl>      <dbl>         <MULTIPOLYGON [°]>
## 1 42003980300       NA        0          0          0 (((-79.9151 40.43139, -79…
## 2 42003980800       NA        0          0          0 (((-79.97292 40.43632, -7…
## 3 42003981100       NA        0          0          0 (((-79.91258 40.44111, -7…
## 4 42003981200       NA        0          0          0 (((-80.01807 40.44888, -8…
## 5 42003980000       NA        0          0          0 (((-79.90163 40.48898, -7…
## 6 42003980700       NA        0          0          0 (((-80.0285 40.44394, -80…
## 7 42003980400       NA        0          0          0 (((-80.026 40.47937, -80.…
## 8 42003980100       NA        0          0          0 (((-79.92481 40.4819, -79…
## 9 42003981000       NA        0          0          0 (((-79.95762 40.47613, -7…
#View these "odd records" on the map
tract_odd <- tract %>% filter(is.na(hhincome)&race.tot==0)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tract) + tm_borders() + tm_shape(pittsburgh) + tm_borders(col = 'darkred') + tm_shape(tract_odd) + tm_borders(col = 'cyan')
#Check if there are any duplicated rows in GEOID
duplicated(tract$GEOID) %>% which()
## integer(0)

No duplicated row in GEOID. These polygons with no income and population data will be retained for now to make sure requesting all the business information within Pittsburgh city.

# 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)
# }
# 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,], "mediterranean"))
#   if (row %% 10 == 0){
#     print(paste0("Current row: ", row))
#   }
# }
# 
# # Collapsing the list into a data.frame
# yelp_mediterra <- yelp_all_list %>% bind_rows() %>% as_tibble()
# 
# # print
# yelp_mediterra %>% print(width=1000)
# Save before-tidied yelp_mediterra to a file
# saveRDS(yelp_mediterra, "yelp_mediterra_raw.rds")
# Read saved .rds file
raw_mediterra <- read_rds("yelp_mediterra_raw.rds")

Question 2. Tidy your data by:

Delete duplicated rows.

Flatten nested columns that have multiple variables in one column. Pay particular attention to the “category” column as it may help you to tell some interesting stories about different types of businesses. If the nested column is empty, you don’t need to flatten it.

Delete rows that have missing data in coordinates variable. It’s okay to have NAs in other variables.

Delete rows that fall outside of the boundary of your choice.

# Check duplicated responses by "id" 
duplicated(raw_mediterra$id) %>% which()
##   [1]   8  10  14  21  23  24  25  31  33  35  37  38  39  40  44  46  47  51
##  [19]  52  53  54  55  56  57  58  60  62  63  64  66  67  69  70  71  72  73
##  [37]  75  76  77  78  79  80  81  82  83  84  86  89  90  91  92  94  95  97
##  [55]  98  99 100 101 102 104 105 106 107 108 109 110 111 112 113 114 115 116
##  [73] 117 118 119 120 121 122 123 124 126 127 128 129 130 131 132 133 135 137
##  [91] 138 139 140 141 142 143 144 145 146 148 149 150 151 152 153 154 155 156
## [109] 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
## [127] 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
## [145] 193 194 195 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
## [163] 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
## [181] 230 231 232 233 234 235 236 237 238 239 240 242 244 245 246 247 248 249
## [199] 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
## [217] 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
## [235] 286 287 288 289 290 291 292 293 294 297 298 299 300 301 302 303 304 305
## [253] 306 307 308 309 310 311 312 313 314 315 316 317 318 319
mediterra_unique <- raw_mediterra %>% 
  distinct(id, .keep_all=T)
glue::glue("Before dropping duplicated rows, there were {nrow(raw_mediterra)} rows. After dropping them, there are {nrow(mediterra_unique)} rows") %>% 
  print()
## Before dropping duplicated rows, there were 319 rows. After dropping them, there are 53 rows
# Take a glimpse of the unique data set
glimpse(mediterra_unique)
## Rows: 53
## Columns: 16
## $ id            <chr> "tqyhUt1OyImr8hT3wQ0a4A", "klls1rEfABAUtO8J0YXSGQ", "7RR…
## $ alias         <chr> "bfg-café-pittsburgh-2", "aladdins-eatery-pittsburgh-squ…
## $ name          <chr> "BFG Café", "Aladdin's Eatery - Pittsburgh-Squirrel Hill…
## $ image_url     <chr> "https://s3-media4.fl.yelpcdn.com/bphoto/6bxcr8-yQm0gFhv…
## $ is_closed     <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, …
## $ url           <chr> "https://www.yelp.com/biz/bfg-caf%C3%A9-pittsburgh-2?adj…
## $ review_count  <int> 66, 235, 23, 42, 19, 5, 18, 43, 49, 28, 1, 126, 9, 379, …
## $ categories    <list> [<data.frame[3 x 2]>], [<data.frame[3 x 2]>], [<data.fr…
## $ rating        <dbl> 4.5, 4.0, 4.0, 4.5, 4.0, 4.0, 4.0, 4.5, 4.5, 4.5, 1.0, 4…
## $ coordinates   <df[,2]> <data.frame[26 x 2]>
## $ transactions  <list> "delivery", <"delivery", "pickup">, <"delivery", "pic…
## $ price         <chr> "$", "$$", NA, "$", "$", NA, NA, NA, NA, NA, NA, "$$", …
## $ location      <df[,8]> <data.frame[26 x 8]>
## $ phone         <chr> "+14126612345", "+14124215100", "+14127276220", "+141280…
## $ display_phone <chr> "(412) 661-2345", "(412) 421-5100", "(412) 727-6220",…
## $ distance      <dbl> 514.0920, 1216.2357, 1106.9232, 989.8377, 1087.1181, 107…

categories, coordinates, transactions and location contain folded data frames.

# 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)
}
mediterra_flat <- mediterra_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(mediterra_flat)
## Rows: 53
## Columns: 24
## $ id                       <chr> "tqyhUt1OyImr8hT3wQ0a4A", "klls1rEfABAUtO8J0Y…
## $ alias                    <chr> "bfg-café-pittsburgh-2", "aladdins-eatery-pit…
## $ name                     <chr> "BFG Café", "Aladdin's Eatery - Pittsburgh-Sq…
## $ image_url                <chr> "https://s3-media4.fl.yelpcdn.com/bphoto/6bxc…
## $ is_closed                <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FAL…
## $ url                      <chr> "https://www.yelp.com/biz/bfg-caf%C3%A9-pitts…
## $ review_count             <int> 66, 235, 23, 42, 19, 5, 18, 43, 49, 28, 1, 12…
## $ categories               <chr> "Pizza, Greek, Mediterranean", "Middle Easter…
## $ rating                   <dbl> 4.5, 4.0, 4.0, 4.5, 4.0, 4.0, 4.0, 4.5, 4.5, …
## $ transactions             <chr> "delivery", "delivery, pickup", "delivery, pi…
## $ price                    <chr> "$", "$$", NA, "$", "$", NA, NA, NA, NA, NA, …
## $ phone                    <chr> "+14126612345", "+14124215100", "+14127276220…
## $ display_phone            <chr> "(412) 661-2345", "(412) 421-5100", "(412) 72…
## $ distance                 <dbl> 514.0920, 1216.2357, 1106.9232, 989.8377, 108…
## $ coordinates.latitude     <dbl> 40.46476, 40.43777, 40.43953, 40.43672, 40.42…
## $ coordinates.longitude    <dbl> -79.93757, -79.91989, -79.89725, -79.95476, -…
## $ location.address1        <chr> "5335 Penn Ave", "5878 Forbes Ave", "7600 For…
## $ location.address2        <chr> "", "", "", NA, NA, NA, "", "", NA, NA, NA, "…
## $ location.address3        <chr> "", "", NA, "", NA, "", NA, NA, "", "", NA, "…
## $ location.city            <chr> "Pittsburgh", "Pittsburgh", "Pittsburgh", "Pi…
## $ location.zip_code        <chr> "15224", "15217", "15221", "15213", "15203", …
## $ location.country         <chr> "US", "US", "US", "US", "US", "US", "US", "US…
## $ location.state           <chr> "PA", "PA", "PA", "PA", "PA", "PA", "PA", "PA…
## $ location.display_address <chr> "5335 Penn Ave, Pittsburgh, PA 15224", "5878 …
# Check missing values
mediterra_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 
##                11                17                18                19

No missing data in coordinates variable.

# Delete responses outside of the tract boundary
mediterra_sf <- mediterra_flat %>% 
  st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"), 
           crs = 4326)
#View the geometries
tm_shape(mediterra_sf) +
  tm_symbols(col = "review_count",
             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")) + 
  tm_shape(tract) + tm_borders() + tm_shape(pittsburgh) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.

Some dots are falling outside of Pittsburgh city boundary and even the tract boundary.

#Set coordinate system
st_crs(pittsburgh) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
# sf subsets
mediterra_pitt <- mediterra_sf[pittsburgh, ,op = st_intersects]
#View the filtered responses
tm_shape(mediterra_pitt) +
  tm_symbols(col = "review_count",
             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")) + 
  tm_shape(pittsburgh) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.

The dots are falling in the city boundary.

Question 3. Tell a short story about finding(s) that interests you (~200 words max).

For example, questions you may consider in your story can include (but not limited to):

Have the findings changed before and after the tidying the data?

glue::glue("nrow before: {nrow(raw_mediterra)} -> nrow after: {nrow(mediterra_pitt)} \n
            ncol before: {ncol(raw_mediterra)} -> ncol after: {ncol(mediterra_pitt)} \n") %>% 
  print()
## nrow before: 319 -> nrow after: 39 
## 
## ncol before: 16 -> ncol after: 23

After tidying the data, unrelated responses are discarded and the features are more detailed.

What’s the most frequent rating score? Does that seem to be related with review_count?

#Reference: https://www.statology.org/mode-in-r/
find_mode <- function(x) {
  u <- unique(x)
  tab <- tabulate(match(x, u))
  u[tab == max(tab)]
}

cat("The most frequent rating score is:", find_mode(mediterra_pitt$rating))
## The most frequent rating score is: 4
#Categorize the number of review count into different frequencies
mediterra_pitt$freq <- cut(mediterra_pitt$review_count,
              breaks=c(0, 10, 100, 300, 1000),
              labels=c('a few', 'some', 'many', 'more'))
mediterra_pitt %>%
  group_by(freq) %>% 
  reframe(rating_mode=find_mode(rating))
## # A tibble: 5 × 2
##   freq  rating_mode
##   <fct>       <dbl>
## 1 a few         4  
## 2 some          4  
## 3 many          4  
## 4 more          4.5
## 5 more          4

Looking at the mode number of the rating, there is not very much difference in rating among different groups of the review_counts.

mediterra_pitt %>%
  group_by(freq) %>% 
  reframe(rating_mean=mean(rating))
## # A tibble: 4 × 2
##   freq  rating_mean
##   <fct>       <dbl>
## 1 a few        3.44
## 2 some         4.09
## 3 many         4.08
## 4 more         4.25

When looking at the mean of the rating, it seems like the higher the review count, the higher the rating tends to be.

(if your Yelp data has price variable) is there any distributional pattern to expensive vs. cheap POIs? Do you think rating and price have some associations? Do you think there is any pattern between the household income and Yelp rating? To answer this question, you will need to also consider Census data.

# census is currently sfc. Convert it to sf.
tract_sf <- tract %>% 
  st_sf(crs = 4326)
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
#Since the household income is in Allegheny county tract data set, all the yelp api responses within the county boundary will be used in the analysis for this question
mediterra_tract <- mediterra_sf[tract_sf, ,op = st_intersects]

# Spatial join
# I want to visualize the polygon so I chose spatial join in the following order
yelp_allegheny <- st_join(mediterra_tract, tract_sf, join = st_intersects)


# number of rows
cat('yelp_allegheny: ', nrow(yelp_allegheny))
## yelp_allegheny:  46
#Exagerate the size difference in terms of rating
yelp_allegheny$rate_exp <- exp(yelp_allegheny$rating)
tm_shape(yelp_allegheny) + 
  tm_symbols(col = "hhincome",
             size="rate_exp",
             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"))+
  tm_shape(tract) + tm_borders()
## Legend for symbol sizes not available in view mode.

Based on the map above, no significant relationship was found between rating and household income. But the number of the review count was not considered in this quick analysis, so more careful analysis is needed in the next step.