Maps assignment

library(tidyverse)
Warning: package 'tidyverse' was built under R version 4.2.3
Warning: package 'ggplot2' was built under R version 4.2.3
Warning: package 'tibble' was built under R version 4.2.3
Warning: package 'tidyr' was built under R version 4.2.3
Warning: package 'readr' was built under R version 4.2.3
Warning: package 'purrr' was built under R version 4.2.3
Warning: package 'dplyr' was built under R version 4.2.3
Warning: package 'stringr' was built under R version 4.2.3
Warning: package 'forcats' was built under R version 4.2.3
Warning: package 'lubridate' was built under R version 4.2.3
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.0     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── 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
library(plotly)
Warning: package 'plotly' was built under R version 4.2.3

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
library(lubridate)
library(scales)
Warning: package 'scales' was built under R version 4.2.3

Attaching package: 'scales'

The following object is masked from 'package:purrr':

    discard

The following object is masked from 'package:readr':

    col_factor
library(tidycensus)      # gets census data that we can use to create maps
Warning: package 'tidycensus' was built under R version 4.2.3
library(sf)              # helper package for mapping
Warning: package 'sf' was built under R version 4.2.3
Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(leaflet)         # interactive mapping package
Warning: package 'leaflet' was built under R version 4.2.3
library(usdata)          # this package has a conversion utility for state abbreviations to full names
Warning: package 'usdata' was built under R version 4.2.3
census_api_key("")
To install your API key for use in future sessions, run this function with `install = TRUE`.
states <- get_acs(geography = "state",               # gets state by state data
                  variables = "B01003_001",          # this is state population
                  geometry = TRUE,                   # gets geometry (the maps)
                  shift_geo = T)                     # shifts Hawaii and Alaska
Getting data from the 2018-2022 5-year ACS
Warning: The `shift_geo` argument is deprecated and will be removed in a future
release. We recommend using `tigris::shift_geometry()` instead.
Warning: • You have not set a Census API key. Users without a key are limited to 500
queries per day and may experience performance limitations.
ℹ For best results, get a Census API key at
http://api.census.gov/data/key_signup.html and then supply the key to the
`census_api_key()` function to use it throughout your tidycensus session.
This warning is displayed once per session.
Using feature geometry obtained from the albersusa package
Please note: Alaska and Hawaii are being shifted and are not to scale.
old-style crs object detected; please recreate object with a recent sf::st_crs()
teenbirth <- read_csv("C:/Users/katri/Downloads/R class/data-table.csv")
Rows: 450 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): STATE, URL
dbl (2): YEAR, RATE

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
 teenbirth_states<- teenbirth |> 
  filter(YEAR == 2017) |> 
  mutate(NAME = abbr2state(STATE)) 
states |> 
  inner_join(teenbirth_states) |> 
  ggplot() + 
  geom_sf(aes(fill = RATE)) + 
  coord_sf(datum = NA) + theme_minimal() +
  scale_fill_viridis_c(labels = label_comma()) +
  labs(title = "Teen birthrates in 2017")
Joining with `by = join_by(NAME)`

1) Choropleth map of the teen birth rate in 2017 using ggplot.

teenbirth_states |>
  ggplot(aes(x = RATE)) +
  geom_histogram()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

2) Histogram of the teen birth rate using ggplot.

states_leaflet <- get_acs(geography = "state",       # gets state by state data
                  variables = "B19013_001",          # this is state income
                  geometry = TRUE,                   # gets geometry (the maps)
                  shift_geo = F)                    # we're not shifting Hawaii and Alaska!
Getting data from the 2018-2022 5-year ACS
Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
teenbirth_colors <- colorNumeric(palette = "viridis", domain = teenbirth_states$RATE) 
  
states_leaflet |>
  inner_join(teenbirth_states) |>
  leaflet() |>
  addTiles() |>
  addPolygons(weight = 1,
              fillColor = ~teenbirth_colors(RATE),
              label = ~paste0(NAME, ", teen birth rate = ", RATE),
              highlight = highlightOptions(weight = 2)) |> 
  setView(-95, 40, zoom = 4) |>
  addLegend(pal = teenbirth_colors, values = ~RATE) 
Joining with `by = join_by(NAME)`
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'

3) Choropleth map using leaflet showing the teen birth rate by state in 2017.

teenbirth_states |> 
  plot_ly(x = ~RATE) |> 
  add_histogram()

4) Histogram using plotly showing the teen birth rate in 2017.

crime_open_database_core_colorado_springs_2017 <- readRDS("C:/Users/katri/Downloads/crime_open_database_core_colorado_springs_2017.Rds")
crime_open_database_core_colorado_springs_2017 |> 
  filter(city_name == "Colorado Springs") |> 
  filter(month(date_single) == 12) |> 
  filter(day(date_single) == 25) -> December_25


December_25
# A tibble: 65 × 12
       uid city_name     offense_code offense_type offense_group offense_against
     <int> <chr>         <chr>        <chr>        <chr>         <chr>          
 1 6955318 Colorado Spr… 22B          non-residen… burglary/bre… property       
 2 6955319 Colorado Spr… 290          destruction… destruction/… property       
 3 6955320 Colorado Spr… 240          motor vehic… motor vehicl… property       
 4 6955321 Colorado Spr… 290          destruction… destruction/… property       
 5 6955322 Colorado Spr… 23F          theft from … larceny/thef… property       
 6 6955323 Colorado Spr… 90Z          all other o… all other of… other          
 7 6955324 Colorado Spr… 13B          simple assa… assault offe… persons        
 8 6955325 Colorado Spr… 23F          theft from … larceny/thef… property       
 9 6955326 Colorado Spr… 240          motor vehic… motor vehicl… property       
10 6955327 Colorado Spr… 22B          non-residen… burglary/bre… property       
# ℹ 55 more rows
# ℹ 6 more variables: date_single <chr>, date_start <chr>, date_end <chr>,
#   longitude <dbl>, latitude <dbl>, census_block <chr>
 December_25|> 
  leaflet() |> 
  addTiles() |>
  addCircleMarkers(stroke = F, fillOpacity = .6, radius = 5, label = ~offense_type)
Assuming "longitude" and "latitude" are longitude and latitude, respectively

5) Dot map (using leaflet) showing offenses that took place in Colorado Springs, Colorado on Christmas day of 2017.

December_25 |>
  count(offense_group, offense_against) |>
  arrange(-n)
# A tibble: 11 × 3
   offense_group                                           offense_against     n
   <chr>                                                   <chr>           <int>
 1 all other offenses                                      other              13
 2 larceny/theft offenses                                  property            9
 3 burglary/breaking & entering                            property            8
 4 motor vehicle theft                                     property            8
 5 driving under the influence                             society             6
 6 assault offenses                                        persons             5
 7 destruction/damage/vandalism of property (except arson) property            5
 8 fraud offenses (except counterfeiting/forgery and bad … property            5
 9 counterfeiting/forgery                                  property            2
10 drug/narcotic offenses                                  society             2
11 trespass of real property                               society             2

6) Table showing the types of offenses and who the offense was against on Christmas day of 2017 in Colorado Springs.