rm(list = ls())
library(yelpr)
library(tidycensus)
library(sf)
## Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; 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.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2
## ── 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)
## 
## 载入程辑包:'reshape2'
## 
## The following object is masked from 'package:tidyr':
## 
##     smiths
library(here)
## here() starts at D:/Storage/Master/23fall/CP6088 Intro to Urban Analytics/6088mini
library(yelpr)
library(knitr)
library(tigris)
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
library(dplyr)
library(sp)
library(here)
library(purrr)

1 Download the Census ACS 5-year estimate data for Census Tracts in Fulton and DeKalb counties, focusing on commuting.

#use census API key
readRenviron("~/.Renviron")
census_api_key <- Sys.getenv("census_api2")
#get census tract boundary
tract <- suppressMessages(
  get_acs(geography = "tract",  
          variables = c(hhincome = 'B19019_001',
                        race.tot = "B02001_001",
                        totCommuteTime = 'B08303_001E',
                        bikeTime='B08136_012M',
                        carTruckVan = "B08006_002E", 
                        publicTrans = 'B08006_008E',
                        bike='B08006_014E',
                        walk='B08006_015E',
                        other='B08006_016E',
                        wfh='B08006_017E'
                        ),
          state = "GA",
          county = c("Fulton", "DeKalb"), 
          year = 2019,
          survey = "acs5", 
          geometry = TRUE, 
          output = "wide") 
)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |==========================================================            |  84%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
tract <- tract %>% 
  select(GEOID, 
         hhincome = hhincomeE, 
         race.tot = race.totE,
         pop_bike=bike,
         bikeTime=bikeTime,
         geometry=geometry
         )
write_rds(tract,file='mini3_tract')

2 Download the City of Atlanta boundary and use it to filter the Census Tracts that either fall within or intersect with the City of Atlanta.

atlanta_boundary <- st_read("border_level8_polygon.geojson")
## Reading layer `sql_statement' from data source 
##   `D:\Storage\Master\23fall\CP6088 Intro to Urban Analytics\6088mini\border_level8_polygon.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 2 features and 13 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -84.55107 ymin: 33.64781 xmax: -84.28956 ymax: 33.88682
## Geodetic CRS:  WGS 84
st_crs(tract)
## Coordinate Reference System:
##   User input: NAD83 
##   wkt:
## GEOGCRS["NAD83",
##     DATUM["North American Datum 1983",
##         ELLIPSOID["GRS 1980",6378137,298.257222101,
##             LENGTHUNIT["metre",1]]],
##     PRIMEM["Greenwich",0,
##         ANGLEUNIT["degree",0.0174532925199433]],
##     CS[ellipsoidal,2],
##         AXIS["latitude",north,
##             ORDER[1],
##             ANGLEUNIT["degree",0.0174532925199433]],
##         AXIS["longitude",east,
##             ORDER[2],
##             ANGLEUNIT["degree",0.0174532925199433]],
##     ID["EPSG",4269]]
st_crs(atlanta_boundary)
## Coordinate Reference System:
##   User input: WGS 84 
##   wkt:
## GEOGCRS["WGS 84",
##     DATUM["World Geodetic System 1984",
##         ELLIPSOID["WGS 84",6378137,298.257223563,
##             LENGTHUNIT["metre",1]]],
##     PRIMEM["Greenwich",0,
##         ANGLEUNIT["degree",0.0174532925199433]],
##     CS[ellipsoidal,2],
##         AXIS["geodetic latitude (Lat)",north,
##             ORDER[1],
##             ANGLEUNIT["degree",0.0174532925199433]],
##         AXIS["geodetic longitude (Lon)",east,
##             ORDER[2],
##             ANGLEUNIT["degree",0.0174532925199433]],
##     ID["EPSG",4326]]
tract <- st_transform(tract, crs = st_crs(atlanta_boundary))
tracts_in_atlanta <- st_intersection(tract, atlanta_boundary)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
#view 
tmap_options(check.and.fix = TRUE)
tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(tracts_in_atlanta) +tm_borders()
## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid

3 Download Yelp data on categories = bikerentals for the City of Atlanta

# Function: Get tract-wise radius
get_r <- function(poly, epsg_id){

  bb <- st_bbox(poly)
  bb_corner <- st_point(c(bb[1], bb[2])) %>% st_sfc(crs = epsg_id)
  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()
  r <- st_distance(bb_corner, bb_center)
  bb_center$radius <- r*1.2
  return(bb_center)
}
#apply this function to each polygon using a functional

epsg_id <- 4326
r4all_apply <- vector("list", nrow(tracts_in_atlanta))

r4all_apply <- tracts_in_atlanta %>%
  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 seprate columns
ready_4_yelp <- r4all_apply %>% 
  mutate(x = st_coordinates(.)[,1],
         y = st_coordinates(.)[,2])
#visualize
tmap_mode('view')
## tmap mode set to interactive viewing
ready_4_yelp[1:10,] %>% 
  st_buffer(., dist = .$radius) %>% 
  tm_shape(.) + tm_polygons(alpha = 0.5, col = 'red') +
  tm_shape(tracts_in_atlanta[1:10,]) + tm_borders(col= 'blue')
## Warning: The shape tracts_in_atlanta[1:10, ] is invalid. See sf::st_is_valid
# function:get_yelp

get_yelp <- function(tract, category){
  Sys.sleep(1)
  n <- 1
  # First request
  resp <- business_search(api_key = Sys.getenv("yelp_api_qq"), 
                          categories = category, 
                          latitude = tract$y, 
                          longitude = tract$x, 
                          offset = (n - 1) * 50, 
                          radius = round(tract$radius), 
                          limit = 50)

  required_n <- as.integer(ceiling(resp$total/50))
  out <- vector("list", required_n)
  out[[n]] <- resp$businesses

  names(out)[n] <- required_n
  
  if (resp$total >= 1000)
  {

    print(glue::glue("{n}th row has >= 1000 businesses."))

    return(out)
  } 
  else 
  {
    n <- n + 1
    # Starting a loop
    while(n <= required_n){
      resp <- business_search(api_key = Sys.getenv("yelp_api_qq"), 
                              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)
  }
}
#run get_yelp
# Looping through all Census Tracts
# choose category: bikerentals


yelp_all_list <- vector("list", nrow(ready_4_yelp))

for (row in 1:nrow(ready_4_yelp)){
  yelp_all_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "bikerentals"))
  if (row %% 10 == 0){
    print(paste0("Current row: ", row))
  }
}
yelp_all <- yelp_all_list %>% bind_rows() %>% as_tibble()

write_rds(yelp_all,file='mini3_yelp_all')

4 Tidy your data by

# 4.1 Deleting duplicated rows.
yelp_all<-read_rds(file='mini3_yelp_all')
ready4tidy<-yelp_all

yelp_dup <- ready4tidy %>% 
  distinct(id, .keep_all=T)

glue::glue("Before dealing with duplicates, there were {nrow(ready4tidy)} rows. After dealing with duplicates, there are {nrow(yelp_dup)} rows") %>%  print()
## Before dealing with duplicates, there were 74 rows. After dealing with duplicates, there are 11 rows
# 4.2 Flattening nested columns that have multiple variables in one column. Pay particular attention to the “category” column.
yelp_flat <- yelp_dup %>% 
  jsonlite::flatten() %>%
  as_tibble() 

yelp_flat$coordinates %>% head()
## Warning: Unknown or uninitialised column: `coordinates`.
## NULL
  # multiple variables in the "categories" column

  # Custom function that takes the data frame in "categories" column in Yelp data
  # and returns a character vector
concate_list <- function(x){
  titles <- x[["title"]] %>% str_c(collapse = ", ")
  return(titles)
}
yelp_concat<-yelp_flat%>%
    mutate(transactions = transactions %>% 
           map_chr(., function(x) str_c(x, collapse=", ")),
         location.display_address = location.display_address %>% 
           map_chr(., function(x) str_c(x, collapse=", ")),
         categories = categories %>% map_chr(concate_list)) 

str(yelp_flat$categories)
## List of 11
##  $ :'data.frame':    2 obs. of  2 variables:
##   ..$ alias: chr [1:2] "bikerentals" "historicaltours"
##   ..$ title: chr [1:2] "Bike Rentals" "Historical Tours"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "bikes" "bike_repair_maintenance" "bikerentals"
##   ..$ title: chr [1:3] "Bikes" "Bike Repair/Maintenance" "Bike Rentals"
##  $ :'data.frame':    2 obs. of  2 variables:
##   ..$ alias: chr [1:2] "scooterrentals" "bikerentals"
##   ..$ title: chr [1:2] "Scooter Rentals" "Bike Rentals"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "bikerentals" "bike_repair_maintenance" "bikes"
##   ..$ title: chr [1:3] "Bike Rentals" "Bike Repair/Maintenance" "Bikes"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "bikes" "bike_repair_maintenance" "bikerentals"
##   ..$ title: chr [1:3] "Bikes" "Bike Repair/Maintenance" "Bike Rentals"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "bike_repair_maintenance" "bikes" "bikerentals"
##   ..$ title: chr [1:3] "Bike Repair/Maintenance" "Bikes" "Bike Rentals"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "bikes" "bikerentals" "bike_repair_maintenance"
##   ..$ title: chr [1:3] "Bikes" "Bike Rentals" "Bike Repair/Maintenance"
##  $ :'data.frame':    2 obs. of  2 variables:
##   ..$ alias: chr [1:2] "bikes" "bikerentals"
##   ..$ title: chr [1:2] "Bikes" "Bike Rentals"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "scooterrentals" "baby_gear" "bikerentals"
##   ..$ title: chr [1:3] "Scooter Rentals" "Baby Gear & Furniture" "Bike Rentals"
##  $ :'data.frame':    3 obs. of  2 variables:
##   ..$ alias: chr [1:3] "smog_check_stations" "bikes" "bikerentals"
##   ..$ title: chr [1:3] "Smog Check Stations" "Bikes" "Bike Rentals"
##  $ :'data.frame':    2 obs. of  2 variables:
##   ..$ alias: chr [1:2] "motorcyclerepair" "bikerentals"
##   ..$ title: chr [1:2] "Motorcycle Repair" "Bike Rentals"
# 4.3 Delete rows that have missing data in coordinates variable and other variables of interest. It’s okay to have NAs in variables that are not of interest.
glue::glue("there are {sum(is.na(yelp_flat$coordinates.latitude))} NA in the latitude column and {sum(is.na(yelp_flat$coordinates.longitude))} NA in the logitude column") %>% 
  print()
## there are 0 NA in the latitude column and 0 NA in the logitude column
yelp_concat %>% 
  map_dbl(., function(x) sum(is.na(x))) 
##                       id                    alias                     name 
##                        0                        0                        0 
##                image_url                is_closed                      url 
##                        0                        0                        0 
##             review_count               categories                   rating 
##                        0                        0                        0 
##             transactions                    phone            display_phone 
##                        0                        0                        0 
##                 distance                    price     coordinates.latitude 
##                        0                        6                        0 
##    coordinates.longitude        location.address1        location.address2 
##                        0                        1                        4 
##        location.address3            location.city        location.zip_code 
##                        3                        0                        0 
##         location.country           location.state location.display_address 
##                        0                        0                        0
# 4.4 Delete rows that fall outside of the City of Atlanta boundary.

# Converting yelp_concat into a sf object
yelp_sf <- yelp_concat %>% 
  st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"), crs = 4326)
tract_sf <- atlanta_boundary%>%st_as_sf(crs=4326)

# sf subsets
yelp_in <- yelp_sf %>% st_intersection(tract_sf)
## Warning: attribute variables are assumed to be spatially constant throughout
## all geometries
glue::glue("nrow before: {nrow(ready4tidy)} -> nrow after: {nrow(yelp_in)} \n
            ncol before: {ncol(ready4tidy)} -> ncol after: {ncol(yelp_in)} \n") %>% 
  print()
## nrow before: 74 -> nrow after: 7 
## 
## ncol before: 16 -> ncol after: 36

5 Examine the associations among the variables bike rentals and bike commuting

# 5.1 Find the right metrics: you may need to create new variables such as proportion, density, etc.
# 5.2 Show at least one graph and at least one map with two variables that you are interested in examining (you can do more!).
# 5.3 (Optional) you can calculate ‘distance to the nearest bike rental store’ for each Census Tract using sf::st_distance().

#what we have
tmap_mode("view")
## tmap mode set to interactive viewing
pop_bike <- tm_shape(tracts_in_atlanta) + tm_polygons("pop_bike")+ tm_shape(yelp_in) + tm_dots(col="red") 
pop <- tm_shape(tracts_in_atlanta) + tm_polygons("race.tot")+tm_shape(yelp_in) + tm_dots(col="red") 
tmap_arrange(pop, pop_bike)
## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid

## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid

## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid

## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid
tracts_in_atlanta$proportion_byBike<-tracts_in_atlanta$pop_bike/tracts_in_atlanta$race.tot
proportion_byBike<-tm_shape(tracts_in_atlanta) + tm_polygons("proportion_byBike")+ tm_shape(yelp_in) + tm_dots(col="red") 
tmap_leaflet(proportion_byBike)
## Warning: The shape tracts_in_atlanta is invalid. See sf::st_is_valid
ggplot(tracts_in_atlanta, aes(x=hhincome, y=proportion_byBike)) +
  geom_point() +  geom_point(color = "black") +  ylab("Proportion of People commute by bike")
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Warning: Removed 3 rows containing missing values (`geom_point()`).