This chunk loads the tidyverse package, which helps us display data visualizations
#1
library(tidyverse)
## ── 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.1 ✔ tibble 3.2.1
## ✔ lubridate 1.9.4 ✔ 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
This chunk reads the Titanic Excel file and displays the first few rows.
#2
titanicdata <- readxl::read_excel("TitanicData-1.xlsx")
head(titanicdata)
## # A tibble: 6 × 6
## pclass survived name sex age fare
## <chr> <chr> <chr> <chr> <dbl> <dbl>
## 1 First Survived Allen, Miss. Elisabeth Walton fema… 29 211.
## 2 First Survived Allison, Master. Hudson Trevor male 0.92 152.
## 3 First Perished Allison, Miss. Helen Loraine fema… 2 152.
## 4 First Perished Allison, Mr. Hudson Joshua Creighton male 30 152.
## 5 First Perished Allison, Mrs. Hudson J C (Bessie Waldo Dani… fema… 25 152.
## 6 First Survived Anderson, Mr. Harry male 48 26.6
This chunk groups the Titanic data by passenger class and survival status by a percentage
#3
pclass_survival <- titanicdata %>%
group_by(pclass, survived) %>%
summarize(n = n()) %>%
mutate(percent = n / sum(n))
## `summarise()` has grouped output by 'pclass'. You can override using the
## `.groups` argument.
pclass_survival
## # A tibble: 6 × 4
## # Groups: pclass [3]
## pclass survived n percent
## <chr> <chr> <int> <dbl>
## 1 First Perished 123 0.381
## 2 First Survived 200 0.619
## 3 Second Perished 158 0.570
## 4 Second Survived 119 0.430
## 5 Third Perished 528 0.745
## 6 Third Survived 181 0.255
This chunk groups the Titanic data by passenger class, gender, and survival status, counts the number in each group, and calculates the percentage for each group.
#4
pclass_sex_survival <- titanicdata %>%
group_by(pclass, sex, survived) %>%
summarize(n = n()) %>%
mutate(percent = n / sum(n))
## `summarise()` has grouped output by 'pclass', 'sex'. You can override using the
## `.groups` argument.
This chunk filters the data to only show passengers who survived as a bar chart
#5
pclass_sex_survival_graph <- pclass_sex_survival %>%
filter(survived == "Survived") %>%
ggplot(mapping = aes(x = pclass, y= percent, fill = pclass)) +
geom_col() +
facet_grid(~sex)
This chunk adds a graph that displays titanic survivial rates in a percentage
#6
pclass_sex_survival_graph +
labs(title ="Titanic Survival Rates",
subtitle = "Percent by Gender and Cabin Class",
caption = "Source: Encyclopedia Titanica") +
scale_y_continuous(labels = scales::percent) +
theme_grey() +
theme(
axis.title=element_blank(),
legend.position = "none"
)