##Introduction This report analyzes survival patterns from the Titanic disaster using the classic Titanic data set. We’ll examine how survival rates were affected by passenger class and gender through statistical tests and visualizations.

#load data
data(titanic_train)
#view data structure
str(titanic_train) #views the column names and data types
## 'data.frame':    891 obs. of  12 variables:
##  $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
##  $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
##  $ Name       : chr  "Braund, Mr. Owen Harris" "Cumings, Mrs. John Bradley (Florence Briggs Thayer)" "Heikkinen, Miss. Laina" "Futrelle, Mrs. Jacques Heath (Lily May Peel)" ...
##  $ Sex        : chr  "male" "female" "female" "female" ...
##  $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
##  $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
##  $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
##  $ Ticket     : chr  "A/5 21171" "PC 17599" "STON/O2. 3101282" "113803" ...
##  $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
##  $ Cabin      : chr  "" "C85" "" "C123" ...
##  $ Embarked   : chr  "S" "C" "S" "S" ...
glimpse(titanic_train)
## Rows: 891
## Columns: 12
## $ PassengerId <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,…
## $ Survived    <int> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1…
## $ Pclass      <int> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2, 3, 1, 3, 3, 3, 2, 3, 2, 3, 3…
## $ Name        <chr> "Braund, Mr. Owen Harris", "Cumings, Mrs. John Bradley (Fl…
## $ Sex         <chr> "male", "female", "female", "female", "male", "male", "mal…
## $ Age         <dbl> 22, 38, 26, 35, 35, NA, 54, 2, 27, 14, 4, 58, 20, 39, 14, …
## $ SibSp       <int> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1, 1, 0, 0, 1, 0, 0, 4, 0, 1, 0…
## $ Parch       <int> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 5, 0, 0, 1, 0, 0, 0…
## $ Ticket      <chr> "A/5 21171", "PC 17599", "STON/O2. 3101282", "113803", "37…
## $ Fare        <dbl> 7.2500, 71.2833, 7.9250, 53.1000, 8.0500, 8.4583, 51.8625,…
## $ Cabin       <chr> "", "C85", "", "C123", "", "", "E46", "", "", "", "G6", "C…
## $ Embarked    <chr> "S", "C", "S", "S", "S", "Q", "S", "S", "S", "C", "S", "S"…
##data cleaning
#remove rows with missing values
titanic_clean<- na.omit(titanic_train)%>% mutate

##convert numerical codes to meaningful factor labels
# Convert survival status (0 = Died, 1 = Survived)
titanic_clean$Survived = factor(titanic_clean$Survived, levels = c(0, 1), labels = c("Died" ,"Survived"))
#  # Convert passenger class (1 = 1st, 2 = 2nd, 3 = 3rd)
titanic_clean$Pclass = factor(titanic_clean$Pclass, 
                levels = c(1, 2, 3), 
                labels = c("1st Class", "2nd Class", "3rd Class"))
# Convert gender to proper labels
titanic_clean$Sex = factor(titanic_clean$Sex, 
             levels = c("male", "female"), 
             labels = c("Male", "Female"))
# Show first few rows of cleaned data
head(titanic_clean)
##   PassengerId Survived    Pclass
## 1           1     Died 3rd Class
## 2           2 Survived 1st Class
## 3           3 Survived 3rd Class
## 4           4 Survived 1st Class
## 5           5     Died 3rd Class
## 7           7     Died 1st Class
##                                                  Name    Sex Age SibSp Parch
## 1                             Braund, Mr. Owen Harris   Male  22     1     0
## 2 Cumings, Mrs. John Bradley (Florence Briggs Thayer) Female  38     1     0
## 3                              Heikkinen, Miss. Laina Female  26     0     0
## 4        Futrelle, Mrs. Jacques Heath (Lily May Peel) Female  35     1     0
## 5                            Allen, Mr. William Henry   Male  35     0     0
## 7                             McCarthy, Mr. Timothy J   Male  54     0     0
##             Ticket    Fare Cabin Embarked
## 1        A/5 21171  7.2500              S
## 2         PC 17599 71.2833   C85        C
## 3 STON/O2. 3101282  7.9250              S
## 4           113803 53.1000  C123        S
## 5           373450  8.0500              S
## 7            17463 51.8625   E46        S

#Explanation 1. Loading Data: We load the built-in Titanic dataset from the titanic package. 2. Data Cleaning: - na.omit() removes rows with missing values - mutate() creates new variables by converting numerical codes to human-readable labels 3. Factor Conversion: - Survival status becomes “Died” (0) or “Survived” (1) - Passenger class becomes “1st Class”, “2nd Class”, “3rd Class” - Gender becomes “Male” or “Female”

##Overall survival rate
# Calculate overall survival proportion
survival_rate <- titanic_clean %>%
  group_by(Survived) %>%
  summarise(Count = n()) %>%
  mutate(Percentage = Count / sum(Count) * 100)
# Create visualization
ggplot(survival_rate, aes(x = "", y = Percentage, fill = Survived)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(round(Percentage), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(title = "Overall Survival Rate on the Titanic",
       fill="Survival Status") +
  scale_fill_manual(values=c("red", "yellow")) +
  theme_void()

#Explanation
- We calculate the count and percentage of passengers who survived vs died
- Visualized as a pie chart with:
  - Red  representing those who died
- yellow  representing survivors
- The percentages show what proportion of passengers survived
#print observed frequencies
print(contingency_table)
##           class
## suvived    1st Class 2nd Class 3rd Class
##   Died            64        90       270
##   Survived       122        83        85
install.packages("ggplot2")
library(ggplot2)
library(scales)
ggplot(titanic_clean, aes(x = Pclass, fill = Survived)) +
  geom_bar(position = "fill") +
  geom_text(aes(label = ..count..), 
            stat = "count", 
            position = position_fill(vjust = 0.5),
            color = "white") +
  scale_y_continuous(labels = percent_format()) +
  labs(title = "Survival Rates by Passenger Class",
       subtitle = "Proportion of passengers who survived in each class",
       x = "Passenger Class",
       y = "Proportion",
       fill = "Survival Status") +
  scale_fill_manual(values = c("#e41a1c", "#4daf4a")) +
  theme_minimal(base_size = 14)

##Chi square test of independence
chi_sq_result<-chisq.test(contingency_table)
 # Format results for display
 results <- data.frame(
   Statistic = c("Chi-Square Value", "Degrees of Freedom", "P-value"),
   Value = c(
     round(chi_sq_result$statistic, 3),
     chi_sq_result$parameter,
     ifelse(chi_sq_result$p.value < 0.001, "< 0.001", round(chisq.test$p.value, 4))
   )
 )
# Print formatted results
 library(knitr)
kable(results, row.names = FALSE,
      caption = "Chi-Square Test Results: Survival vs Passenger Class")
Chi-Square Test Results: Survival vs Passenger Class
Statistic Value
Chi-Square Value 92.901
Degrees of Freedom 2
P-value < 0.001
### Interpretation

Conclusion: There is a statistically significant relationship between passenger class and survival (χ²(2) = 92.9, p < 0.001). First-class passengers had significantly higher survival rates than other classes.


``` r
##Analysis 2: SUrvival by gender
#Create a contingency tacble of survival by gender
gender_table <- table(
   Survival = titanic_clean$Survived,
   Gender = titanic_clean$Sex
 )
# Print formatted table
 kable(gender_table, 
       caption = "Observed Frequencies: Survival by Gender")
Observed Frequencies: Survival by Gender
Male Female
Died 360 64
Survived 93 197
 ##visualization;survival by gender
  # Create stacked bar plot showing survival by gender
 ggplot(titanic_clean, aes(x = Sex, fill = Survived)) +
   geom_bar(position = "fill") +
   geom_text(aes(label = ..count..), 
             stat = "count", 
             position = position_fill(vjust = 0.5),
             color = "white") +
   scale_y_continuous(labels = percent_format()) +
   labs(title = "Survival Rates by Gender",
        subtitle = "Proportion of males and females who survived",
        x = "Gender",
        y = "Proportion",
        fill = "Survival Status") +
   scale_fill_manual(values = c("#e41a1c", "#4daf4a")) +
   theme_minimal(base_size = 14)

 ##Chi square test for independence
 # Perform chi-square test
 gender_test <- chisq.test(gender_table)
 
 # Format results for display
 gender_results <- data.frame(
   Statistic = c("Chi-Square Value", "Degrees of Freedom", "P-value"),
   Value = c(
     round(gender_test$statistic, 3),
     gender_test$parameter,
     ifelse(gender_test$p.value < 0.001, "< 0.001", round(gender_test$p.value, 4))
   )
 )
 # Print formatted results
kable(gender_results, row.names = FALSE, 
      caption = "Chi-Square Test Results: Survival vs Gender")
Chi-Square Test Results: Survival vs Gender
Statistic Value
Chi-Square Value 205.026
Degrees of Freedom 1
P-value < 0.001

Interpretation

## **Conclusion:** There is a statistically significant relationship between gender and survival (χ²(1) = 205.03, p < 0.001). Females had significantly higher survival rates than males.

Explanation:

This visualization shows how survival rates differed based on both passenger class and gender: - Each panel represents a passenger class (1st, 2nd, 3rd) - Within each panel, we see survival rates for males and females - Key insights: 1. Females consistently had higher survival rates than males 2. Survival advantage was strongest for 1st class females 3. 3rd class males had the lowest survival rate


Key Findings Summary

  1. Overall Survival: Only 40.6% of passengers survived
  2. Class Impact:
    • 1st class passengers had highest survival rate
    • Survival decreased with each lower class
    • Chi-square test showed significant relationship (p < 0.001)
  3. Gender Impact:
    • Females had much higher survival rate than males
    • Chi-square test showed significant relationship (p < 0.001)
  4. Combined Effect:
    • 1st class females had the highest survival rate
    • 3rd class males had the lowest survival rate

These patterns reflect the historical “women and children first” protocol, with class privilege also playing a significant role in survival outcomes.

## **Conclusion:** There is a statistically significant relationship between gender and survival (χ²(1) = 205.03, p < 0.001). Females had significantly higher survival rates than males.

## **Conclusion:** There is a statistically significant relationship between passenger class and survival (χ²(2) = 92.9, p < 0.001). First-class passengers had significantly higher survival rates than other classes.