library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ 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
library(ggthemes)
library(ggrepel)
library(broom)
library(lindia)
my_data <- read.csv("/Users/shemaaeltayeb/Desktop/STATISTIC IN R /student_data.csv")

PART 1:

Select an interesting binary column of data, or one which can be reasonably converted into a binary variable.

The “internet” column represents whether the student has internet access at home, and it’s a binary variable with values 1 for ‘yes’, 0 for ‘no’. This binary variable can be interesting to analyze because access to the internet can have a significant impact on a student’s academic performance, research capabilities, and overall learning experience. Will explore how internet access at home relates to various outcomes in the dataset, such as final grades, study time, or participation in extracurricular activities.

PART 2:

Build a logistic regression model for this variable, using between 1-4 explanatory variables Interpret the coefficients, and explain what they mean in your notebook.

(Bonus) Using the Standard Error for at least one coefficient, build a C.I. for that coefficient, and interpret its meaning

Will build a logistic regression for the internet response variable with the final grades as explanatory variables.

# Create a new column 'internet_binary' from the internet column:

my_data$internet_binary <- ifelse(my_data$internet == "yes", 1, 0)
# Count of Binary values(0 for no internet, 1 for yes there is an internet) in the 'internet_binary' column:
print(table(my_data$internet_binary))
## 
##   0   1 
##  66 329

**Represent the relationship between the final grade (G3) and response variable (internet_binary).

my_data |>
  ggplot(mapping = aes(x = G3, y = internet_binary)) +
  geom_jitter(width = 0, height = 0.1, shape = 'O', size = 3) +
  geom_smooth(method = 'lm', se = FALSE) +
  labs(title = "Modeling a Binary Response Internet With Final Grade") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

The straight regression line indicates a linear relationship between final grades and the transformed binary response. The line starts at a high point (0.8) and remains relatively constant, that means the probability of having internet access is high across various grades. This might indicate that students with different grades have a consistent likelihood of having internet access.

Most of the data points are located above the regression line, particularly in the grade range of 8 to 15. This suggests that within this grade range,most of students are likely to have internet access according to the transformed response variable.

** Logistic Regression Model Fitting and Extract coefficients from the model:

# Fit a logistic regression model
model <- glm(internet_binary ~ G3, data = my_data, family = binomial(link = 'logit'))

# Extract coefficients from the model
 model$coefficients
## (Intercept)          G3 
##  1.05579685  0.05489124

Based on this output, the intercept indicates that there is a baseline probability of having internet access (albeit low) even if the final grade is very low. However, the positive coefficient for G3 suggests that as a student’s final grade improves, the probability of having internet access also increases, although the effect is relatively small.

In summary, the logistic regression model confirms a positive relationship between final grades and the likelihood of having internet access, so students with internet access tend to have better grades, with a relatively small effect size.

** Visualizing a logistic regression model using the sigmoid function based on the coefficients:

# these coefficients come from the model
sigmoid <- \(x) 1 / (1 + exp(-(1.05579685 + 0.05489124 * x)))

my_data|>
  ggplot(mapping = aes(x = G3, y = internet_binary)) +
  geom_jitter(width = 0, height = 0.1, shape = 'O', size = 3) +
  geom_function(fun = sigmoid, color = 'blue', linewidth = 1) +
  labs(title = "Modeling a Binary Response with Sigmoid") +
  scale_y_continuous(breaks = c(0, 0.5, 1)) +
  theme_minimal()

Using the Standard Error for at least one coefficient, build a C.I. for that coefficient, and interpret its meaning:

# View the summary of the regression model
summary(model)
## 
## Call:
## glm(formula = internet_binary ~ G3, family = binomial(link = "logit"), 
##     data = my_data)
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  1.05580    0.30422   3.471 0.000519 ***
## G3           0.05489    0.02823   1.945 0.051812 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 356.48  on 394  degrees of freedom
## Residual deviance: 352.78  on 393  degrees of freedom
## AIC: 356.78
## 
## Number of Fisher Scoring iterations: 4

Based on the summary output, the logistic regression model’s coefficient for the variable G3 is estimated to be 0.05489 with a standard error of 0.02823. To construct a 95% confidence interval (CI) for this coefficient. Will do this code:

# Calculate the confidence interval for the coefficient of G3

ci <- confint(model, "G3")
## Waiting for profiling to be done...
# Print the confidence interval

print(ci)
##        2.5 %       97.5 % 
## -0.001074711  0.109953570

The output provided represents the 95% confidence interval for the coefficient of G3 in the logistic regression model. In this case, the interval is (−0.001074711,0.109953570) Lower Bound (−0.001074711):The lower limit of the confidence interval indicates that, according to the model, the effect of the variable G3 on the log-odds of having internet is estimated to be as low as approximately −0.001074711. Upper Bound (0.109953570):The upper limit of the confidence interval indicates that the effect of the variable G3 on the log-odds of having internet is estimated to be as high as approximately0.109953570. This means that the relationship between having internet and having a high grade, by the variable G3, is not statistically significant at the 0.05 level.

#Will build a logistic regression for the internet response variable with using the study time as explanatory variables

** Model the relationship between study time (studytime) and the binary response variable internet_binary.

my_data |>
  ggplot(mapping = aes(x = studytime, y = internet_binary)) +
  geom_jitter(width = 0, height = 0.1, shape = 'O', size = 3) +
  geom_smooth(method = 'lm', se = FALSE) +
  labs(title = "Modeling a Binary Response Internet With Final Grade") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

The straight regression line indicate a positive relationship between study time and the likelihood of having internet access. As study time increases, the probability of having internet access also seems to increase, although the relationship might not be very strong.

Most data points are clustered around study times 1 and 2, with the likelihood of internet access around 0.8. This indicates that students with study times of 1 or 2 hours are more likely to have internet access. For study time 3 and 4, the likelihood of internet access is slightly lower but still above 0.5.

Study Time 4: There are fewer students with a study time of 4 hours, which makes it difficult to draw strong conclusions about internet access for this specific study time category due to the limited data.

In summary, the plot suggests that students with study times of 1 and 2 hours are more likely to have internet access, while the likelihood decreases for study times 3 and 4.

** Fit a logistic regression model and Extract coefficients from the model:

# Fit a logistic regression model
model_studytime <- glm(internet_binary ~ studytime, data = my_data, family = binomial(link = 'logit'))

# Extract coefficients from the model
 model$coefficients
## (Intercept)          G3 
##  1.05579685  0.05489124

This means that students who spend more hours studying are more likely to have internet access, and for every one-hour increase in study time, the odds of having internet access increase by around 21.8%.

** Visualizing a logistic regression model using the sigmoid function based on the coefficients:

# these coefficients come from the model
sigmoid <- \(x) 1 / (1 + exp(-( 1.2133159  + 0.1975509  * x)))

my_data|>
  ggplot(mapping = aes(x = studytime, y = internet_binary)) +
  geom_jitter(width = 0, height = 0.1, shape = 'O', size = 3) +
  geom_function(fun = sigmoid, color = 'blue', linewidth = 1) +
  labs(title = "Modeling a Binary Response with Sigmoid") +
  scale_y_continuous(breaks = c(0, 0.5, 1)) +
  theme_minimal()

PART 3:

Consider a transformation for any explanatory variable, and illustrate why you need the transformation (or why you do not). Scatter Plots.

# Create a scatter plot with a line between G3 and internet
ggplot(my_data, aes(x = G3, y = internet_binary)) +
  geom_jitter(width = 0.1, height = 0.1, shape = 16, size = 3, color = "lightblue") +
  geom_smooth(method = "glm", method.args = list(family = "binomial"), se = FALSE, color = "red") +
  labs(title = "Scatter Plot with Line: G3 vs. Internet",
       x = "Final Grade (G3)",
       y = "Internet (Binary)") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

This plot displays individual data points as well as a red line representing the logistic regression relationship between G3 and internet.

In data analysis, transformations are usually unnecessary when the relationship between variables is already linear and are easier to understand and interpret. They follow a straightforward pattern: as one variable increases, the other either increases or decreases at a constant rate.

Transformations might be applied when the relationship is non-linear, aiming to make it linear.