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)
my_data <- read.csv("/Users/shemaaeltayeb/Desktop/STATISTIC IN R /student_data.csv")
Build at least three sets of variable combinations:
*For each set of variables, include at least one column that you created (i.e., calculated based on others)
*All variables for this data dive should be either continuous (i.e., numeric) or ordered (e.g., [‘small’, ‘medium’, ‘large’] is okay, but [“apples”, “oranges”, “bananas”] is not)
*For each set, there should be one response variable with the others as explanatory variables
Deviation: To calculate the deviation of each student’s G3 score from the mean G3 score. This can help identify students who performed significantly better or worse than the average. It could be an important feature for predicting G3 because it quantifies how much a student’s score deviates from the norm.
my_data <- my_data %>%
mutate(g3_deviation = G3 - mean(G3))
Rank Ordering: To create a rank order variable based on G3 scores. This can be useful to categorize students into different performance groups. For example, create categories like “Low Performers,” “Medium Performers,” and “High Performers” based on their G3 ranks.
my_data <- my_data %>%
mutate(g3_rank = factor(rank(G3)))
Difference: Calculate the difference between G3 and another related variable. For example, calculate the difference between G3 and G2 (second-period grade) to see if improvements or declines in performance from one period to another affect G3.
my_data <- my_data %>%
mutate(g3_g2_difference = G3 - G2)
Grouping age into categories makes the results more interpretable for a broader audience. People find it easier to relate to age groups (e.g., “under 18,” “18-20,” “21-25”) than individual ages. Will be easier to understand and analyze and can help in creating more straightforward visualizations and summarizing information.
#convert the "age" variable into groups:
my_data <- my_data %>%
mutate(age_group = cut(age,
breaks = c(10,15, 20,Inf),
labels = c("10-15", "15-20","20-25"),
right = TRUE))
Converting the “sex” column into numeric values ( 0 for female and 1 for male).
my_data$numeric_sex <- ifelse(my_data$sex == "F", 0, 1)
Create a new column “G3_group” that contains the group labels for the “G3” variable based on the specified intervals.
# Create groups for G3 variable:
my_data <- my_data %>%
mutate(G3_group = cut(G3, breaks = c(0, 5, 10, 15, 20, 25), labels = c("0-5", "5-10", "10-15", "15-20","20-25"), right = FALSE))
Create a new column with ordered G3 values from low to high.
my_data <- my_data %>%
arrange(G3) %>%
mutate(G3_ordered = factor(G3, levels = unique(G3)))
Response Variable: Final Grade (G3)
Explanatory Variables:
Mother education (Medu) Father education (Fedu) Family relationship quality (famrel) Free time (freetime) Health (health)
Creating this set to identify and understand the factors that influence a student’s performance, particularly their final grade (G3), based on variables such as maternal education (Medu), paternal education (Fedu), family relationship quality (famrel), free time (freetime), and overall health (health).
Response Variable: Final Grade (G3)
Explanatory Variables:
Study Time (studytime) Absences (absences) Previous Failures (failures) Previous Grades (G1 and G2)
Creating this set can perform various analyses to understand how study time, absences, previous failures, and previous grades (G1 and G2) relate to a student’s final grade (G3).
Plot a visualization for each response-explanatory relationship, and draw some conclusions based on the plot. Use what we’ve covered so far in class to scrutinize the plot (e.g., are there any outliers?)
# Select the columns for set one
set_one <- my_data %>%
select(G3, Medu, Fedu, famrel, freetime, health)
# Check the first few rows of set one
#head(set_one)
# Load necessary library
library(ggplot2)
# Scatter plot: G3 vs Medu
ggplot(set_one, aes(y = Medu, x = G3)) +
geom_point() +
labs(y = "Mother education (Medu)", x = "Final Grade (G3)")
# Scatter plot: G3 vs Fedu
ggplot(set_one, aes(y = Fedu, x = G3)) +
geom_point() +
labs(y = "Father education (Fedu)", x = "Final Grade (G3)")
# Scatter plot: G3 vs famrel
ggplot(set_one, aes(y = famrel, x = G3)) +
geom_point() +
labs(y = "Family relationship quality (famrel)", x = "Final Grade (G3)")
# Scatter plot: G3 vs freetime
ggplot(set_one, aes(y = freetime, x= G3)) +
geom_point() +
labs(y = "Free time", x = "Final Grade (G3)")
# Scatter plot: G3 vs health
ggplot(set_one, aes(y = health, x = G3)) +
geom_point() +
labs(y = "Health", x = "Final Grade (G3)")
It appears from the visualization that family relationship quality, mother’s education (Medu), and father’s education (Fedu) have an impact on the final grade (G3) of students. However, there doesn’t seem to be a significant correlation between the final grade and students’ health.
This suggests that family dynamics and parental education might play a more substantial role in students’ academic performance compared to their health status.
# Select the columns for set two
set_two <- my_data %>%
select(G3, Dalc, Walc ,goout , age , traveltime)
# Load necessary library
library(ggplot2)
# Scatter plot: G3 vs Dalc
ggplot(set_two, aes(y = Dalc, x = G3)) +
geom_point() +
labs(y = "Weekday Alcohol Consumption (Dalc)", x = "Final Grade (G3)")
# Scatter plot: G3 vs Walc
ggplot(set_two, aes(y = Walc, x = G3)) +
geom_point() +
labs(y = "Weekend Alcohol Consumption (Walc)", x = "Final Grade (G3)")
# Scatter plot: G3 vs goout
ggplot(set_two, aes(y = goout, x = G3)) +
geom_point() +
labs(y = "Going Out (goout)", x = "Final Grade (G3)")
# Scatter plot: G3 vs age
ggplot(set_two, aes(y = age, x= G3)) +
geom_point() +
labs(y = "Age", x = "Final Grade (G3)")
# Scatter plot: G3 vs health
ggplot(set_two, aes(y = traveltime, x = G3)) +
geom_point() +
labs(y = "Travel Time", x = "Final Grade (G3)")
The visualization indicates that higher weekday alcohol consumption tends to correspond with lower final grades. Students who consume alcohol more frequently on weekdays are likely to have lower grades. This suggests a negative correlation between weekday alcohol consumption and academic performance.
Students who consume alcohol primarily on weekends (lower Walc) seem to have a slightly better chance of achieving higher grades compared to those who consume alcohol more frequently on weekdays (higher Dalc). Weekend alcohol consumption appears to have a lesser negative impact on grades compared to weekday consumption.
The analysis suggests that there is not a significant linear relationship between age and final grades. In other words, the age of the student doesn’t appear to strongly influence the final grade. There might be other factors at play that affect academic performance more directly.
The visualization indicates that as travel time increases, final grades tend to decrease. Students who spend more time traveling from home to school are likely to have lower grades. This suggests a negative correlation between travel time and academic performance.
In summary, weekday alcohol consumption (Dalc), weekend alcohol consumption (Walc), and travel time to school are factors that appear to influence final grades in set_two. Specifically, higher alcohol consumption, especially on weekdays, and longer travel times are associated with lower academic performance. Age, however, does not show a strong linear correlation with final grades in this analysis.
# Select the columns for set three
set_three <- my_data %>%
select(G3,studytime , absences , failures, G1 , G2)
# Scatter plot for G3 vs absences
ggplot(set_three, aes(y = absences, x = G3)) +
geom_point(color = "skyblue", alpha = 0.7) +
labs(y = "Number of Absences", x = "Final Grade (G3)") +
theme_minimal()
# Scatter plot for G3 vs studytime
ggplot(set_three, aes(y = studytime , x = G3)) +
geom_point(color = "skyblue", alpha = 0.7) +
labs(y = "studytime", x = "Final Grade (G3)") +
theme_minimal()
# Scatter plot for G3 vs G2
ggplot(set_three, aes(y = G2 , x = G3)) +
geom_point(color = "skyblue", alpha = 0.7) +
labs(y = "G2", x = "Final Grade (G3)") +
theme_minimal()
# Scatter plot for G3 vs G1
ggplot(set_three, aes(y = G1 , x = G3)) +
geom_point(color = "skyblue", alpha = 0.7) +
labs(y = "G1", x = "Final Grade (G3)") +
theme_minimal()
# Scatter plot for G3 vs failures
ggplot(set_three, aes(y = failures , x = G3)) +
geom_point(color = "skyblue", alpha = 0.7) +
labs(y = "Failures", x = "Final Grade (G3)") +
theme_minimal()
G1 and G2 (First and Second Period Grades): These variables have a strong positive correlation with the final grade (G3). It’s common for students who perform well in the earlier periods to also perform well in the final period.
Absences: There is a negative correlation between absences and final grades. More absences tend to be associated with lower final grades. High absenteeism can indicate missed lessons and could impact a student’s understanding of the material.
Studytime: the study time doesn’t strongly influence final grades. It’s possible that other factors might be more influential in determining a student’s academic performance.
Failures: There is a clear negative correlation between past failures and final grades. Students who have failed previous classes tend to have lower final grades. This highlights the importance of addressing past academic challenges to improve overall performance.
These insights provide valuable information for understanding the factors that impact student performance in set_three. Further analysis and modeling could help explore these relationships in more depth and potentially predict student outcomes based on these factors.
Calculate the appropriate correlation coefficient for each of these combinations.
Explain why the value makes sense (or doesn’t) based on the visualization(s).
# correlation coefficient for set_one:
round(cor(set_one$G3, set_one$Medu), 2)
## [1] 0.22
round(cor(set_one$G3, set_one$Fedu), 2)
## [1] 0.15
round(cor(set_one$G3, set_one$famrel), 2)
## [1] 0.05
round(cor(set_one$G3, set_one$freetime), 2)
## [1] 0.01
round(cor(set_one$G3, set_one$health), 2)
## [1] -0.06
Correlation Analysis:
G3 and Medu (Mother’s Education): The correlation coefficient is 0.22. This positive correlation suggests a weak positive relationship between a student’s final grade and their mother’s education level. As mother’s education level increases, the final grade tends to increase slightly.
G3 and Fedu (Father’s Education): The correlation coefficient is 0.15. Similar to mother’s education, there is a weak positive relationship between a student’s final grade and their father’s education level. As father’s education level increases, the final grade tends to increase, though the effect is relatively weak.
G3 and Famrel (Family Relationship Quality): The correlation coefficient is 0.05. There is a very weak positive relationship between family relationship quality and the final grade. A higher family relationship quality is associated with a slightly higher final grade, but the effect is minimal.
G3 and Freetime (Free Time): The correlation coefficient is 0.01. There is an extremely weak positive relationship between free time and the final grade. This indicates that free time does not significantly influence a student’s final grade in set_one.
G3 and Health: The correlation coefficient is -0.06. This negative correlation suggests a weak negative relationship between a student’s final grade and their health. As health decreases (worsens), the final grade tends to decrease slightly.
That means the correlations in set_one indicate weak to very weak relationships between the final grade and these explanatory variables. The strongest relationship exists with mother’s education, followed by father’s education, while family relationship quality, free time, and health have minimal influence on the final grade.
# correlation coefficient for set_two:
round(cor(set_two$G3, set_two$Dalc), 2)
## [1] -0.05
round(cor(set_two$G3, set_two$Walc), 2)
## [1] -0.05
round(cor(set_two$G3, set_two$goout), 2)
## [1] -0.13
round(cor(set_two$G3, set_two$age), 2)
## [1] -0.16
round(cor(set_two$G3, set_two$traveltime), 2)
## [1] -0.12
G3 and Dalc (Weekday Alcohol Consumption): The correlation coefficient is -0.05. This negative correlation suggests a very weak negative relationship between a student’s final grade and their weekday alcohol consumption. As weekday alcohol consumption increases slightly, the final grade tends to decrease very slightly, but the effect is minimal.
G3 and Walc (Weekend Alcohol Consumption): The correlation coefficient is -0.05. Similar to weekday alcohol consumption, there is a very weak negative relationship between weekend alcohol consumption and the final grade. As weekend alcohol consumption increases slightly, the final grade tends to decrease very slightly.
G3 and Goout (Going Out with Friends): The correlation coefficient is -0.13. There is a weak negative relationship between how often a student goes out with friends and the final grade. As the frequency of going out increases, the final grade tends to decrease slightly. The effect, while weak, is more noticeable compared to alcohol consumption.
G3 and Age: The correlation coefficient is -0.16. There is a weak negative relationship between a student’s age and the final grade. As a student’s age increases, the final grade tends to decrease slightly. This suggests that older students might, on average, have slightly lower final grades compared to younger students.
G3 and Traveltime: The correlation coefficient is -0.12. There is a weak negative relationship between travel time from home to school and the final grade. As travel time increases, indicating a longer commute, the final grade tends to decrease slightly. Students with longer travel times may have slightly lower final grades on average.
Since these factors in set_two exhibit weak negative relationships with the final grade. While the correlations are statistically significant due to the dataset’s size, the actual impact on the final grade is minimal for each of these factors.
# correlation coefficient for set_three:
round(cor(set_three$G3, set_three$studytime), 2)
## [1] 0.1
round(cor(set_three$G3, set_three$absences), 2)
## [1] 0.03
round(cor(set_three$G3, set_three$failures), 2)
## [1] -0.36
round(cor(set_three$G3, set_three$G1), 2)
## [1] 0.8
round(cor(set_three$G3, set_three$G2), 2)
## [1] 0.9
Study Time (studytime) vs. Final Grade (G3) [0.1]:
There is a weak positive correlation between study time and final grades. While there is a positive trend, it’s not very strong, indicating that increased study time only slightly influences higher grades.
Absences vs. Final Grade (G3) [0.03]:
The correlation between absences and final grades is very weak and positive. This suggests that there is almost no linear relationship between the number of absences and final grades.
Past Failures (failures) vs. Final Grade (G3) [-0.36]:
There is a moderate negative correlation between past failures and final grades. A higher number of past failures is associated with lower final grades. This negative correlation indicates that students who have failed before are likely to have lower final grades.
First Period Grade (G1) vs. Final Grade (G3) [0.8]:
There is a very strong positive correlation between the first period grade (G1) and the final grade (G3). This means that students who perform well in the first period are highly likely to perform well in the final period.
Second Period Grade (G2) vs. Final Grade (G3) [0.9]: The correlation between the second period grade (G2) and the final grade (G3) is extremely strong, indicating that students who do well in the second period also do exceptionally well in the final period.
These correlations provide insights into the relationships between different variables and the final grade (G3). The strong positive correlations with G1 and G2 suggest that early academic performance is highly predictive of final grades. On the other hand, the negative correlation with failures indicates the impact of past academic difficulties on current performance. The weak correlations with study time and absences suggest that these factors have limited influence on final grades in this dataset.
Build a confidence interval for each of the response variables. Provide a detailed conclusion of the response variable (i.e., the population) based on your confidence interval.
** Average for the G3 from the entire dataset (All Students):
This gives overall average final grade for all students in the dataset. It provides a general overview of the students’ performance.
average_whole_dataset <- mean(my_data$G3)
print(average_whole_dataset)
## [1] 10.41519
** Average for G3 from Set One (Family Relationship Factors):
This represents the average final grade for students filtered based on variables like mother’s education, father’s education, family relationship quality, free time, and health. It helps understand the average performance of students within specific family-related conditions.
average_set_one <- mean(set_one$G3)
print(average_set_one)
## [1] 10.41519
** Average from Set Two (Alcohol Consumption and Social Activities):
This shows the average final grade for students filtered based on variables like weekday alcohol consumption, weekend alcohol consumption, going out with friends, age, and travel time. It gives insights into how students’ social activities and alcohol consumption patterns relate to their grades.
average_set_two <- mean(set_two$G3)
print(average_set_two)
## [1] 10.41519
** Average from Set Three:
average_set_three <- mean(set_three$G3)
print(average_set_three)
## [1] 10.41519
Having a similar average across subsets could indicate that factors like family background, social habits, or academic history are not disproportionately influencing students’ grades.
Further exploration is needed to understand and explore what impact the overall average grade ?
# Load necessary libraries
library(boot)
# Function to calculate confidence interval using bootstrapping
calculate_ci <- function(data, response_var, conf_level = 0.95, n_iter = 1000) {
boot_func <- function(data, indices) {
sample_data <- data[indices, ]
mean_val <- mean(sample_data[[response_var]], na.rm = TRUE)
return(mean_val)
}
# Perform bootstrapping
boot_results <- boot(data, boot_func, R = n_iter)
# Calculate confidence intervals using basic percentile intervals
ci <- boot.ci(boot_results, conf = conf_level, type = "perc")
return(ci)
}
# Example usage for response variable G3
g3_ci <- calculate_ci(my_data, "G3")
# Print confidence intervals
print(g3_ci)
## BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
## Based on 1000 bootstrap replicates
##
## CALL :
## boot.ci(boot.out = boot_results, conf = conf_level, type = "perc")
##
## Intervals :
## Level Percentile
## 95% ( 9.94, 10.85 )
## Calculations and Intervals on Original Scale
The analysis for the response variable, the final grade (G3), based on the provided confidence interval (CI):The calculated average for G3 from every data set is 10.41519 and it is within this confidence interval ( 9.96, 10.86 ).
Interpretation of the Confidence Interval (CI):
Lower Bound: 9.96 Upper Bound: 10.86 Level of Confidence: 95%
Conclusion:
The 95% confidence interval (9.96, 10.86) suggests that can be reasonably confident that the true average final grade for the population falls within this range. That means , if repeatedly sample from the same population and calculate the average final grade, we expect it to fall between 9.96 and 10.86 in 95% of these samples.
Detailed Analysis:
Below 9.96: Any final grade below 9.96 might be considered below average, based on this analysis. Students scoring below this value could be facing challenges impacting their academic performance.
Between 9.96 and 10.86: Final grades within this range are statistically consistent with the average performance. Students falling within this interval can be considered to have an average academic performance based on the dataset.
Above 10.86: Any final grade above 10.86 could be considered above average. Students scoring above this value are statistically performing better than the average student in the dataset.
Educational Implications:
Schools might focus on students scoring below 9.96, offering additional support, tutoring, or counseling to help them improve academically.
Students within the range of 9.96 to 10.86 might be considered academically stable.
Students performing above 10.86 could be identified for advanced programs or additional challenges to keep them engaged and motivated.
The analysis assumes that the dataset is representative of the entire student population. External factors not considered in the dataset (such as socioeconomic background, mental health, or teaching methods) might influence final grades.
Overall, the confidence interval provides a valuable tool for understanding the range within which the true average final grade lies, allowing for informed decision-making and targeted interventions in the educational context.