Certainly! Here’s your script formatted as an R Markdown document:
# Assuming the file is already downloaded and placed in the working directory
titanic_path <- "C:/Users/jawii/Downloads/titanic3.csv"
T3 <- read.csv(titanic_path)
titanic <- T3[, c("survived", "embarked", "sex", "sibsp", "parch", "fare")]
summary(titanic)
## survived embarked sex sibsp
## Min. :0.000 Length:1309 Length:1309 Min. :0.0000
## 1st Qu.:0.000 Class :character Class :character 1st Qu.:0.0000
## Median :0.000 Mode :character Mode :character Median :0.0000
## Mean :0.382 Mean :0.4989
## 3rd Qu.:1.000 3rd Qu.:1.0000
## Max. :1.000 Max. :8.0000
##
## parch fare
## Min. :0.000 Min. : 0.000
## 1st Qu.:0.000 1st Qu.: 7.896
## Median :0.000 Median : 14.454
## Mean :0.385 Mean : 33.295
## 3rd Qu.:0.000 3rd Qu.: 31.275
## Max. :9.000 Max. :512.329
## NA's :1
prop_survived <- prop.table(table(titanic$survived))
# View the proportions
prop_survived
##
## 0 1
## 0.618029 0.381971
titanic <- na.omit(titanic)
titanic$survived <- factor(titanic$survived)
titanic$embarked <- factor(titanic$embarked)
titanic$sex <- factor(titanic$sex)
library(vcd)
## Warning: package 'vcd' was built under R version 4.3.3
## Loading required package: grid
# Calculate Cramér's V for the relationship between 'survived' and 'sex'
cramer_v_sex <- assocstats(table(titanic$survived, titanic$sex))$cramer
cramer_v_embarked <- assocstats(table(titanic$survived, titanic$embarked))$cramer
# View the Cramér's V statistics
cramer_v_sex
## [1] 0.5272478
cramer_v_embarked
## [1] 0.1837218
library(ggplot2)
ggplot(titanic, aes(x = sex, fill = survived)) +
geom_bar(position = "dodge")
set.seed(1000)
train_index <- sample(1:nrow(titanic), 0.8 * nrow(titanic))
train <- titanic[train_index, ]
test <- titanic[-train_index, ]
library(rpart)
## Warning: package 'rpart' was built under R version 4.3.3
library(rattle)
## Warning: package 'rattle' was built under R version 4.3.3
## Loading required package: tibble
## Loading required package: bitops
## Rattle: A free graphical interface for data science with R.
## Version 5.5.1 Copyright (c) 2006-2021 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
fit <- rpart(survived ~ sex + sibsp + parch + fare + embarked,
data = train, method = "class")
library(rpart.plot)
## Warning: package 'rpart.plot' was built under R version 4.3.3
pdf("regression_tree.pdf")
rpart.plot(fit)
dev.off()
## png
## 2
fancyRpartPlot(fit)
# Tree splits over gender first
# Children are the future so they should be saved first. When it comes to the adults I believe in equality.
prediction <- predict(fit, test, type = "class")
Results <- data.frame(passengersex = test$sex, survived = prediction)
write.csv(Results, file = "Titanicdtree.csv", row.names = FALSE)
```
This R Markdown document includes the code chunks for each step along with the comments and the corresponding output. When you knit this document, it will generate an HTML file with the analysis and outputs included.