Created
August 16, 2022 03:19
-
-
Save gadenbuie/dc33547225425eb8106a6ed0c27013aa to your computer and use it in GitHub Desktop.
From date to month to columns with a crosstab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(lubridate) | |
# https://data.cityofchicago.org/Public-Safety/Crimes-2015/vwwp-7yr9 | |
crimes <- read_csv("crimes.csv", lazy = TRUE, show_col_types = FALSE) | |
crimes |> | |
slice_sample(n = 500) |> | |
mutate( | |
Date = mdy_hms(Date), | |
month_name = month(Date, label = TRUE, abbr = FALSE) | |
) |> | |
count(month_name, `Primary Type`) |> | |
pivot_wider( | |
names_from = month_name, | |
values_from = n, | |
values_fill = 0 | |
) | |
#> # A tibble: 20 × 13 | |
#> `Primary Type` January February March April May June July August | |
#> <chr> <int> <int> <int> <int> <int> <int> <int> <int> | |
#> 1 ASSAULT 5 0 6 0 6 2 3 0 | |
#> 2 BATTERY 4 8 10 15 4 14 10 7 | |
#> 3 BURGLARY 2 2 1 1 1 1 0 0 | |
#> 4 CRIMINAL DAMAGE 7 7 5 7 5 4 6 4 | |
#> 5 CRIMINAL TRESPASS 2 0 1 1 3 0 2 0 | |
#> 6 DECEPTIVE PRACTICE 3 3 1 1 3 3 4 4 | |
#> 7 MOTOR VEHICLE THEFT 1 1 1 2 0 2 4 4 | |
#> 8 NARCOTICS 3 3 4 2 3 5 3 0 | |
#> 9 OFFENSE INVOLVING CHIL… 2 0 0 0 1 0 0 1 | |
#> 10 OTHER OFFENSE 2 1 1 4 2 2 1 2 | |
#> 11 ROBBERY 1 0 3 2 3 4 3 0 | |
#> 12 THEFT 6 9 9 10 11 13 11 9 | |
#> 13 PUBLIC PEACE VIOLATION 0 1 2 0 0 0 1 0 | |
#> 14 CRIM SEXUAL ASSAULT 0 0 2 0 0 0 0 1 | |
#> 15 PUBLIC INDECENCY 0 0 1 0 0 0 0 0 | |
#> 16 PROSTITUTION 0 0 0 1 0 0 0 0 | |
#> 17 WEAPONS VIOLATION 0 0 0 2 1 0 0 1 | |
#> 18 HOMICIDE 0 0 0 0 1 0 0 0 | |
#> 19 GAMBLING 0 0 0 0 0 0 0 1 | |
#> 20 ARSON 0 0 0 0 0 0 0 0 | |
#> # … with 4 more variables: September <int>, October <int>, November <int>, | |
#> # December <int> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment