Skip to content

Instantly share code, notes, and snippets.

@Hychhayrith
Last active March 28, 2021 14:21
Show Gist options
  • Save Hychhayrith/262550f13bc23de5e42592583999129e to your computer and use it in GitHub Desktop.
Save Hychhayrith/262550f13bc23de5e42592583999129e to your computer and use it in GitHub Desktop.
Habit Health Relativity
library(readxl)
# import dataset
ds <- read_excel("HHR.xlsx")
library(magrittr)
colnames(ds)
library(dplyr)
# linear model
ds$exercise_freq <- as.factor(ds$exercise_freq)
ds$year <- as.integer(ds$year)
linear <- lm(year ~ exercise_freq, data = ds)
summary(linear)
library(ggplot2)
ggplot(ds, aes(x=exercise_freq, y=year, color=factor(gender)))+
geom_point() +
stat_smooth(method = "lm", se=TRUE)
ggsave(filename = "GenderFactorInExerciseFreq.png",
units = "cm",
width = 25,
height = 15)
# find the predicted, residual values and add it into the dataset
ds$x_predicted <- predict(linear)
ds$x_residual <- residuals(linear)
# plot graph and save as image
png(filename = "LinearGraph.png")
plot(linear)
dev.off()
# graph using ggplot and save as image
png(filename = "FinalGraph.png")
ggplot(ds, aes(exercise_freq, year)) +
geom_point(color = "blue") +
geom_point(aes(y = x_predicted), color = "red") +
geom_segment(aes(xend = gender, yend = x_predicted)) +
geom_smooth(method = "lm", color = "black")
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment