HeartDisease

Sahar Yousofi

2023-12-08

Issue Description

This data analysis project is dedicated to exploring the prevalence and risk factors associated with heart disease, a significant global health issue that burdens healthcare systems and leads to substantial morbidity and mortality. Recent reports and medical research continually underscore the importance of understanding and mitigating heart disease. According to the World Health Organization (WHO), cardiovascular diseases, including heart disease, account for approximately 17.9 million deaths worldwide each year. In light of the increasing prevalence of heart disease risk factors, such as hypertension, high cholesterol, obesity, and sedentary lifestyles, it is crucial to investigate these factors and develop tools for early risk assessment. This analysis is not only vital for healthcare professionals but also offers the potential for personalized risk assessment, thus contributing to global efforts to alleviate the heart disease burden.

Questions

1.How do exercise habits or body condition elements like Max-Hr, fasting BS, and chest pain influence heart disease risk? Can we gauge the importance of these factors in predicting heart disease?

2.Is there a gender-based distinction in the risk factors and prevalence of heart disease? Are particular risk factors more pronounced in one gender than the other?

Data Source

The dataset includes — records and 14 attributes. The attributes cover a range of health metrics and demographic information that are relevant for analyzing heart disease risk factors and building predictive models. Some of the attributes include age, gender, chest pain type, blood pressure, cholesterol levels, and more. DataSource: https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction

getwd()
## [1] "C:/Users/user/Desktop/Fall'23 SMU/CSC 530"
setwd("C:/Users/user/Desktop/Fall'23 SMU/CSC 530")
##install.packages("readr")
#install.packages("randomForest")
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.2.3
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
library(readr)
## Warning: package 'readr' was built under R version 4.2.3
library(tidymodels)
## Warning: package 'tidymodels' was built under R version 4.2.3
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ recipes      1.0.8
## ✔ dials        1.2.0     ✔ rsample      1.2.0
## ✔ dplyr        1.1.3     ✔ tibble       3.2.1
## ✔ ggplot2      3.4.3     ✔ tidyr        1.3.0
## ✔ infer        1.0.5     ✔ tune         1.1.2
## ✔ modeldata    1.2.0     ✔ workflows    1.1.3
## ✔ parsnip      1.1.1     ✔ workflowsets 1.0.1
## ✔ purrr        1.0.2     ✔ yardstick    1.2.0
## Warning: package 'broom' was built under R version 4.2.3
## Warning: package 'dials' was built under R version 4.2.3
## Warning: package 'dplyr' was built under R version 4.2.3
## Warning: package 'ggplot2' was built under R version 4.2.3
## Warning: package 'infer' was built under R version 4.2.3
## Warning: package 'modeldata' was built under R version 4.2.3
## Warning: package 'parsnip' was built under R version 4.2.3
## Warning: package 'purrr' was built under R version 4.2.3
## Warning: package 'recipes' was built under R version 4.2.3
## Warning: package 'rsample' was built under R version 4.2.3
## Warning: package 'tibble' was built under R version 4.2.3
## Warning: package 'tidyr' was built under R version 4.2.3
## Warning: package 'tune' was built under R version 4.2.3
## Warning: package 'workflows' was built under R version 4.2.3
## Warning: package 'workflowsets' was built under R version 4.2.3
## Warning: package 'yardstick' was built under R version 4.2.3
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ dplyr::combine()  masks randomForest::combine()
## ✖ purrr::discard()  masks scales::discard()
## ✖ dplyr::filter()   masks stats::filter()
## ✖ dplyr::lag()      masks stats::lag()
## ✖ ggplot2::margin() masks randomForest::margin()
## ✖ yardstick::spec() masks readr::spec()
## ✖ recipes::step()   masks stats::step()
## • Use tidymodels_prefer() to resolve common conflicts.
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.3
## Warning: package 'stringr' was built under R version 4.2.3
## Warning: package 'forcats' was built under R version 4.2.3
## Warning: package 'lubridate' was built under R version 4.2.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.3
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ scales::col_factor() masks readr::col_factor()
## ✖ dplyr::combine()     masks randomForest::combine()
## ✖ purrr::discard()     masks scales::discard()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ stringr::fixed()     masks recipes::fixed()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ ggplot2::margin()    masks randomForest::margin()
## ✖ yardstick::spec()    masks readr::spec()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)
library(dplyr)
library(pROC)
## Warning: package 'pROC' was built under R version 4.2.3
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## 
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
heartdf = read_csv("heart1.csv")
## Rows: 918 Columns: 12
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): Sex, ChestPainType, RestingECG, ExerciseAngina, ST_Slope
## dbl (7): Age, RestingBP, Cholesterol, FastingBS, MaxHR, Oldpeak, HeartDisease
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Documentation

https://www.kaggle.com/datasets/fedesoriano/heart-failure-prediction/

Description of the Data

This data-set has 12 attributes. The data classifies if patients have heart disease or not (HeartDisease) according to features in it. For this project I will try to answer simple questions about influence if elements and gender classification on heart disease risk and predict the results.

str(heartdf)
## spc_tbl_ [918 × 12] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Age           : num [1:918] 40 49 37 48 54 39 45 54 37 48 ...
##  $ Sex           : chr [1:918] "M" "F" "M" "F" ...
##  $ ChestPainType : chr [1:918] "ATA" "NAP" "ATA" "ASY" ...
##  $ RestingBP     : num [1:918] 140 160 130 138 150 120 130 110 140 120 ...
##  $ Cholesterol   : num [1:918] 289 180 283 214 195 339 237 208 207 284 ...
##  $ FastingBS     : num [1:918] 0 0 0 0 0 0 0 0 0 0 ...
##  $ RestingECG    : chr [1:918] "Normal" "Normal" "ST" "Normal" ...
##  $ MaxHR         : num [1:918] 172 156 98 108 122 170 170 142 130 120 ...
##  $ ExerciseAngina: chr [1:918] "N" "N" "N" "Y" ...
##  $ Oldpeak       : num [1:918] 0 1 0 1.5 0 0 0 0 1.5 0 ...
##  $ ST_Slope      : chr [1:918] "Up" "Flat" "Up" "Flat" ...
##  $ HeartDisease  : num [1:918] 0 1 0 1 0 0 0 0 1 0 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Age = col_double(),
##   ..   Sex = col_character(),
##   ..   ChestPainType = col_character(),
##   ..   RestingBP = col_double(),
##   ..   Cholesterol = col_double(),
##   ..   FastingBS = col_double(),
##   ..   RestingECG = col_character(),
##   ..   MaxHR = col_double(),
##   ..   ExerciseAngina = col_character(),
##   ..   Oldpeak = col_double(),
##   ..   ST_Slope = col_character(),
##   ..   HeartDisease = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>
summary(heartdf)
##       Age            Sex            ChestPainType        RestingBP    
##  Min.   :28.00   Length:918         Length:918         Min.   :  0.0  
##  1st Qu.:47.00   Class :character   Class :character   1st Qu.:120.0  
##  Median :54.00   Mode  :character   Mode  :character   Median :130.0  
##  Mean   :53.51                                         Mean   :132.4  
##  3rd Qu.:60.00                                         3rd Qu.:140.0  
##  Max.   :77.00                                         Max.   :200.0  
##   Cholesterol      FastingBS       RestingECG            MaxHR      
##  Min.   :  0.0   Min.   :0.0000   Length:918         Min.   : 60.0  
##  1st Qu.:173.2   1st Qu.:0.0000   Class :character   1st Qu.:120.0  
##  Median :223.0   Median :0.0000   Mode  :character   Median :138.0  
##  Mean   :198.8   Mean   :0.2331                      Mean   :136.8  
##  3rd Qu.:267.0   3rd Qu.:0.0000                      3rd Qu.:156.0  
##  Max.   :603.0   Max.   :1.0000                      Max.   :202.0  
##  ExerciseAngina        Oldpeak          ST_Slope          HeartDisease   
##  Length:918         Min.   :-2.6000   Length:918         Min.   :0.0000  
##  Class :character   1st Qu.: 0.0000   Class :character   1st Qu.:0.0000  
##  Mode  :character   Median : 0.6000   Mode  :character   Median :1.0000  
##                     Mean   : 0.8874                      Mean   :0.5534  
##                     3rd Qu.: 1.5000                      3rd Qu.:1.0000  
##                     Max.   : 6.2000                      Max.   :1.0000

Cleaning and Preparation

Describe the steps you took to get from your original dataset to the final dataset you used for your analysis. Include the R code in chunks.

## Check for NA values in the dataset
na_summary <- colSums(is.na(heartdf))

## Print the summary
print(na_summary)
##            Age            Sex  ChestPainType      RestingBP    Cholesterol 
##              0              0              0              0              0 
##      FastingBS     RestingECG          MaxHR ExerciseAngina        Oldpeak 
##              0              0              0              0              0 
##       ST_Slope   HeartDisease 
##              0              0
## Handle Missing Values: There are no missing values but in case there will be in future updates it will be usefull.
heartdf <- heartdf[complete.cases(heartdf),]
head(heartdf)
## # A tibble: 6 × 12
##     Age Sex   ChestPainType RestingBP Cholesterol FastingBS RestingECG MaxHR
##   <dbl> <chr> <chr>             <dbl>       <dbl>     <dbl> <chr>      <dbl>
## 1    40 M     ATA                 140         289         0 Normal       172
## 2    49 F     NAP                 160         180         0 Normal       156
## 3    37 M     ATA                 130         283         0 ST            98
## 4    48 F     ASY                 138         214         0 Normal       108
## 5    54 M     NAP                 150         195         0 Normal       122
## 6    39 M     NAP                 120         339         0 Normal       170
## # ℹ 4 more variables: ExerciseAngina <chr>, Oldpeak <dbl>, ST_Slope <chr>,
## #   HeartDisease <dbl>
# Convert Categorical Variables to Factors: Considering this step for statistical modeling (lm or glm), visualization package (ggplot), accurate categorical representation of the cat vars, and some default functions:

categorical_vars <- c("Sex", "ChestPainType", "RestingECG", "ExerciseAngina", "ST_Slope")

for (var in categorical_vars) {
  heartdf[[var]] <- as.factor(heartdf[[var]])
}
str(heartdf)
## tibble [918 × 12] (S3: tbl_df/tbl/data.frame)
##  $ Age           : num [1:918] 40 49 37 48 54 39 45 54 37 48 ...
##  $ Sex           : Factor w/ 2 levels "F","M": 2 1 2 1 2 2 1 2 2 1 ...
##  $ ChestPainType : Factor w/ 4 levels "ASY","ATA","NAP",..: 2 3 2 1 3 3 2 2 1 2 ...
##  $ RestingBP     : num [1:918] 140 160 130 138 150 120 130 110 140 120 ...
##  $ Cholesterol   : num [1:918] 289 180 283 214 195 339 237 208 207 284 ...
##  $ FastingBS     : num [1:918] 0 0 0 0 0 0 0 0 0 0 ...
##  $ RestingECG    : Factor w/ 3 levels "LVH","Normal",..: 2 2 3 2 2 2 2 2 2 2 ...
##  $ MaxHR         : num [1:918] 172 156 98 108 122 170 170 142 130 120 ...
##  $ ExerciseAngina: Factor w/ 2 levels "N","Y": 1 1 1 2 1 1 1 1 2 1 ...
##  $ Oldpeak       : num [1:918] 0 1 0 1.5 0 0 0 0 1.5 0 ...
##  $ ST_Slope      : Factor w/ 3 levels "Down","Flat",..: 3 2 3 2 3 3 3 3 2 3 ...
##  $ HeartDisease  : num [1:918] 0 1 0 1 0 0 0 0 1 0 ...
nrow(heartdf)
## [1] 918
# Check and Handle Unusual Values in Categorical Variables
for (var in categorical_vars) {
  unique_values <- unique(heartdf[[var]])
  print(paste("Unique values in", var, ":", toString(unique_values)))

## Handle unusual values 
  invalid_values <- unique_values[!(unique_values %in% levels(heartdf[[var]]))]

  if (length(invalid_values) > 0) {
    ## Replace invalid values with NA or a standard category
    heartdf[[var]] <- factor(heartdf[[var]], levels = c(levels(heartdf[[var]]), invalid_values))
    heartdf[[var]][heartdf[[var]] %in% invalid_values] <- NA
  }
}
## [1] "Unique values in Sex : M, F"
## [1] "Unique values in ChestPainType : ATA, NAP, ASY, TA"
## [1] "Unique values in RestingECG : Normal, ST, LVH"
## [1] "Unique values in ExerciseAngina : N, Y"
## [1] "Unique values in ST_Slope : Up, Flat, Down"
str(heartdf)
## tibble [918 × 12] (S3: tbl_df/tbl/data.frame)
##  $ Age           : num [1:918] 40 49 37 48 54 39 45 54 37 48 ...
##  $ Sex           : Factor w/ 2 levels "F","M": 2 1 2 1 2 2 1 2 2 1 ...
##  $ ChestPainType : Factor w/ 4 levels "ASY","ATA","NAP",..: 2 3 2 1 3 3 2 2 1 2 ...
##  $ RestingBP     : num [1:918] 140 160 130 138 150 120 130 110 140 120 ...
##  $ Cholesterol   : num [1:918] 289 180 283 214 195 339 237 208 207 284 ...
##  $ FastingBS     : num [1:918] 0 0 0 0 0 0 0 0 0 0 ...
##  $ RestingECG    : Factor w/ 3 levels "LVH","Normal",..: 2 2 3 2 2 2 2 2 2 2 ...
##  $ MaxHR         : num [1:918] 172 156 98 108 122 170 170 142 130 120 ...
##  $ ExerciseAngina: Factor w/ 2 levels "N","Y": 1 1 1 2 1 1 1 1 2 1 ...
##  $ Oldpeak       : num [1:918] 0 1 0 1.5 0 0 0 0 1.5 0 ...
##  $ ST_Slope      : Factor w/ 3 levels "Down","Flat",..: 3 2 3 2 3 3 3 3 2 3 ...
##  $ HeartDisease  : num [1:918] 0 1 0 1 0 0 0 0 1 0 ...

Final Results

Show how you approached the questions you posed at the beginning. Describe how much you were able to accomplish. There should be both graphical and numerical results produced by R code included in chunks. Explain what you did and what it means.

##Question One: 1.How do exercise habits or body condition elements like Max-Hr, fasting BS, and chest pain influence heart disease risk? Can we gauge the importance of these factors in predicting heart disease?

# Exploratory Data Analysis (EDA)
## Scatter plot for Age vs. MaxHR colored by Heart Disease status
ggplot(heartdf, aes(x = Age, y = MaxHR, color = factor(HeartDisease))) +
  geom_point() +
  labs(title = "Age vs. MaxHR by Heart Disease Status")

## Boxplot for Oldpeak by Heart Disease status
ggplot(heartdf, aes(x = factor(HeartDisease), y = Oldpeak)) +
  geom_boxplot() +
  labs(title = "Oldpeak by Heart Disease Status")

## Create a subset of the dataset with relevant columns
lifestyle_df <- heartdf %>%
  select(Sex, FastingBS, ExerciseAngina, Oldpeak, HeartDisease)

# Visualize the distribution of Oldpeak by Heart Disease status
ggplot(lifestyle_df, aes(x = Oldpeak, fill = factor(HeartDisease))) +
  geom_density(alpha = 0.5) +
  labs(title = "Distribution of Oldpeak by Heart Disease Status",
       x = "Oldpeak",
       y = "Density",
       fill = "Heart Disease")

## Visualize the relationship between ExerciseAngina and Heart Disease
ggplot(lifestyle_df, aes(x = ExerciseAngina, fill = factor(HeartDisease))) +
  geom_bar(position = "fill") +
  labs(title = "Proportion of Heart Disease Cases by Exercise-Induced Angina",
       x = "Exercise-Induced Angina",
       y = "Proportion",
       fill = "Heart Disease")

## Visualize the distribution of FastingBS by Heart Disease status
ggplot(lifestyle_df, aes(x = factor(FastingBS), fill = factor(HeartDisease))) +
  geom_bar(position = "fill") +
  labs(title = "Proportion of Heart Disease Cases by Fasting Blood Sugar",
       x = "Fasting Blood Sugar",
       y = "Proportion",
       fill = "Heart Disease")

## Bar plot for ChestPainType
ggplot(heartdf, aes(x = ChestPainType, fill = factor(HeartDisease))) +
  geom_bar(position = "dodge") +
  labs(title = "Distribution of ChestPainType by Heart Disease Status")

# Bar plot for RestingECG
ggplot(heartdf, aes(x = RestingECG, fill = factor(HeartDisease))) +
  geom_bar(position = "dodge") +
  labs(title = "Distribution of RestingECG by Heart Disease Status")

## Bar plot for ST_Slope
ggplot(heartdf, aes(x = ST_Slope, fill = factor(HeartDisease))) +
  geom_bar(position = "dodge") +
  labs(title = "Distribution of ST_Slope by Heart Disease Status")

## Check for multicollinearity among selected features
heartdf$ExerciseAngina <- as.numeric(as.character(heartdf$ExerciseAngina))
## Warning: NAs introduced by coercion
cor_matrix <- cor(heartdf[, c("FastingBS", "ExerciseAngina", "Oldpeak")])
print("Correlation Matrix:")
## [1] "Correlation Matrix:"
print(cor_matrix)
##                 FastingBS ExerciseAngina    Oldpeak
## FastingBS      1.00000000             NA 0.05269786
## ExerciseAngina         NA              1         NA
## Oldpeak        0.05269786             NA 1.00000000
# Split the data into training and testing sets
set.seed(123)
split_index <- sample(1:nrow(heartdf), 0.7 * nrow(heartdf))
train_data <- heartdf[split_index, ]
test_data <- heartdf[-split_index, ]

## Train a machine learning model (e.g., logistic regression)
heartdf$ExerciseAngina <- as.factor(heartdf$ExerciseAngina)
model <- glm(HeartDisease ~ FastingBS + MaxHR + Oldpeak, data = train_data, family = "binomial")

## Make predictions on the test set
predictions <- predict(model, newdata = test_data, type = "response")

# Evaluate model performance
## Confusion matrix
conf_matrix <- table(Predicted = ifelse(predictions > 0.5, 1, 0), Actual = test_data$HeartDisease)
print("Confusion Matrix:")
## [1] "Confusion Matrix:"
print(conf_matrix)
##          Actual
## Predicted   0   1
##         0  93  35
##         1  28 120
## Calculate accuracy
accuracy <- sum(diag(conf_matrix)) / sum(conf_matrix)
print(paste("Accuracy:", accuracy))
## [1] "Accuracy: 0.771739130434783"
## ROC curve
roc_curve <- roc(test_data$HeartDisease, predictions)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_curve, main = "ROC Curve", col = "blue")

auc <- auc(roc_curve)
print
## function (x, ...) 
## UseMethod("print")
## <bytecode: 0x00000252bb0e9a48>
## <environment: namespace:base>

##Anwer: The logistic regression model aimed at understanding the impact of exercise and body condition elements on heart disease risk produced the following insights:

  1. Correlation Matrix: The correlation analysis detected potential missing or non-numeric values (here non-numeric) in the data set, particularly in the variables FastingBS, ExerciseAngina, and Oldpeak.

  2. Confusion Matrix: Assessing the model’s performance through a confusion matrix revealed:

  1. 93 accurate predictions of individuals without heart disease (True Negatives).
  2. 120 accurate predictions of individuals with heart disease (True Positives).
  3. 35 incorrect predictions of individuals with heart disease (False Positives).
  4. 28 incorrect predictions of individuals without heart disease (False Negatives).
  1. Accuracy: The overall accuracy of the model stands at around 77.17%, indicating a satisfactory level of correctness in predicting heart disease status.

In conclusion, while the model demonstrates reasonable accuracy, attention is needed to address potential issues with non-numeric values in certain variables. Further exploration of evaluation metrics like precision, recall, and F1-score could provide a more nuanced understanding. Refinement and consideration of additional features may enhance the model’s predictive capacity for lifestyle and body condition elements influencing heart disease risk.

#Question Two: 2.Is there a gender-based distinction in the risk factors and prevalence of heart disease? Are particular risk factors more pronounced in one gender than the other?

## Gender Distribution
ggplot(heartdf, aes(x = Sex, fill = factor(HeartDisease))) +
  geom_bar(position = "dodge") +
  labs(title = "Distribution of Heart Disease by Gender")

## Risk Factors by Gender
ggplot(heartdf, aes(x = Sex, y = RestingBP, fill = factor(HeartDisease))) +
  geom_boxplot() +
  labs(title = "Resting Blood Pressure by Gender and Heart Disease Status")

## Risk Factors by Gender
ggplot(heartdf, aes(x = Sex, y = Cholesterol, fill = factor(HeartDisease))) +
  geom_boxplot() +
  labs(title = "Cholestrol by Gender and Heart Disease Status")

## Risk Factors by Gender
ggplot(heartdf, aes(x = Sex, y = MaxHR, fill = factor(HeartDisease))) +
  geom_boxplot() +
  labs(title = "Max Hear Rate by Gender and Heart Disease Status")

# Prevalence of Heart Disease by Gender
ggplot(heartdf, aes(x = Sex, fill = factor(HeartDisease))) +
  geom_bar(position = "dodge") +
  labs(title = "Prevalence of Heart Disease by Gender")

## Statistical Tests

## t-test for RestingBP by Gender
R_test_result <- t.test(RestingBP ~ Sex, data = heartdf)
print(R_test_result)
## 
##  Welch Two Sample t-test
## 
## data:  RestingBP by Sex
## t = -0.15015, df = 289.36, p-value = 0.8808
## alternative hypothesis: true difference in means between group F and group M is not equal to 0
## 95 percent confidence interval:
##  -3.288430  2.822266
## sample estimates:
## mean in group F mean in group M 
##        132.2124        132.4455
## t-test for Cholesterol by Gender
C_test_result <- t.test(Cholesterol ~ Sex, data = heartdf)
print(C_test_result)
## 
##  Welch Two Sample t-test
## 
## data:  Cholesterol by Sex
## t = 7.2375, df = 388.83, p-value = 2.459e-12
## alternative hypothesis: true difference in means between group F and group M is not equal to 0
## 95 percent confidence interval:
##  39.10048 68.26709
## sample estimates:
## mean in group F mean in group M 
##        241.1969        187.5131
## t-test for MaxHR by Gender
M_test_result <- t.test(MaxHR ~ Sex, data = heartdf)
print(M_test_result)
## 
##  Welch Two Sample t-test
## 
## data:  MaxHR by Sex
## t = 6.3555, df = 342.77, p-value = 6.621e-10
## alternative hypothesis: true difference in means between group F and group M is not equal to 0
## 95 percent confidence interval:
##   8.158048 15.470710
## sample estimates:
## mean in group F mean in group M 
##        146.1399        134.3255

#Answer: RestingBP by Sex: The test comparing mean resting blood pressure (RestingBP) between genders found no significant difference (p-value = 0.8808). The mean difference is minimal, and the confidence interval ranges from -3.29 to 2.82.

Cholesterol by Sex: A significant difference in mean cholesterol levels between genders was observed (p-value < 0.001), with females (group F) having a higher mean (241.20) compared to males (group M, mean = 187.51).

MaxHR by Sex: A significant difference in mean maximum heart rates between genders was found (p-value < 0.001), indicating higher rates in females (mean = 146.14) than males (mean = 134.33).

To sum up, the analysis on RestingBP suggests no notable gender difference, but significant distinctions are found in Cholesterol and MaxHR. These results offer valuable insights into potential gender-related variations in heart disease risk factors. Yet, delving deeper into factors affecting cholesterol and heart rates among genders could offer crucial insights for personalized health interventions and heart disease risk assessment. For example, exploring additional variables and their influence on cardiovascular health can be a good approach.

nrow(heartdf)
## [1] 918
## Convert Sex to a factor
heartdf$Sex <- as.factor(heartdf$Sex)

# Split the data into training and testing sets
set.seed(123)
split_index <- sample(1:nrow(heartdf), 0.7 * nrow(heartdf))
train_data <- heartdf[split_index, ]
test_data <- heartdf[-split_index, ]

## Train a logistic regression model
model_logistic <- glm(HeartDisease ~ Sex + RestingBP + Cholesterol + MaxHR + Oldpeak, data = train_data, family = "binomial")

## Make predictions on the test set
predictions_logistic <- predict(model_logistic, newdata = test_data, type = "response")

## Convert predictions to binary (0 or 1)
binary_predictions_logistic <- ifelse(predictions_logistic > 0.5, 1, 0)

## Confusion matrix
conf_matrix_logistic <- table(Predicted = binary_predictions_logistic, Actual = test_data$HeartDisease)
print(conf_matrix_logistic)
##          Actual
## Predicted   0   1
##         0  88  33
##         1  33 122
## Calculate accuracy
accuracy_logistic <- sum(diag(conf_matrix_logistic)) / sum(conf_matrix_logistic)
print(paste("Accuracy:", accuracy_logistic))
## [1] "Accuracy: 0.760869565217391"

##Answer: The model’s accuracy is around 76.09%, meaning it correctly predicted heart disease status in that percentage of cases. Specifically, it accurately identified 88 cases without heart disease and 122 cases with heart disease. However, there were 33 instances of false positives and 33 instances of false negatives. While the model is reasonably accurate, there’s room for improvement, suggesting potential enhancements in feature selection or model refinement to boost predictive performance.

Note: TN (0,0): 88 cases were correctly predicted as not having heart disease. TP (1,1): 122 cases were correctly predicted as having heart disease. FP (1,0): 33 cases were incorrectly predicted as having heart disease when they did not. FN (0,1): 33 cases were incorrectly predicted as not having heart disease when they did.