Data Programming

Homework 5

Author

Mirko Dugajlić

Published

June 2, 2024

Libraries

library(tidyverse)
library(ggplot2)

Solutions

Load datasets

df <- read.csv2("files/dataset.csv")
df_states <- read.csv2("files/state_abbreviations_and_populations.csv")

1. Show the number of fatalities per state (full name of state required). Futhermore, plot the results wth a histogram.

# Make left join of two tables/datasets
ljoin <- left_join(df, df_states, by=c("State" = "Abbreviation")) %>%
  filter(!is.na(Name.y))

df_to_plot <- ljoin %>% 
  group_by(State = Name.y) %>%
  summarise(n = n())

as.tibble(df_to_plot)
# A tibble: 51 × 2
   State                    n
   <chr>                <int>
 1 Alabama                691
 2 Alaska                 126
 3 Arizona                900
 4 Arkansas               384
 5 California            4892
 6 Colorado               673
 7 Connecticut            142
 8 Delaware                63
 9 District of Columbia    88
10 Florida               1851
# ℹ 41 more rows
ggplot(df_to_plot, aes(y=State, weight = n))+geom_bar()

2. Plot death by gender across race with a histogram, entirely with R, not with markdown/quarto!

# Group dataframe by race and gender
df_to_plot <- df %>%
  group_by(Gender, Race) %>%
  summarise(n=n())

ggplot(df_to_plot, aes(y=Race, weight = n)) +
  geom_bar() +
  facet_wrap(~Gender, scales = "free_x")

3. Plot the outline of the USA by scatterploting the locations of deaths.

# Convert Longitude and Latitude to numeric
df_to_plot <- df %>%
  mutate(
    Longitude = as.numeric(Longitude, na.rm=T),
    Latitude = as.numeric(Latitude, na.rm=T)
  )

# Calculate min and max of longitude & latitude
xlim_min <- min(df_to_plot$Longitude, na.rm = T)
xlim_max <- max(df_to_plot$Longitude, na.rm = T)

ylim_min <- min(df_to_plot$Latitude, na.rm = T)
ylim_max <- max(df_to_plot$Latitude, na.rm = T)

# Plot USA 
ggplot() +
  geom_point(data = df_to_plot, aes(x = Longitude, y = Latitude)) +
  xlim(xlim_min, xlim_max) +
  ylim(ylim_min, ylim_max)