# 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.
# 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.
# 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.
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.