Skip to content

Instantly share code, notes, and snippets.

@darioappsilon
Created December 22, 2020 09:24
Show Gist options
  • Save darioappsilon/fb7b8fe2e0c973c40ac68f35317efe5b to your computer and use it in GitHub Desktop.
Save darioappsilon/fb7b8fe2e0c973c40ac68f35317efe5b to your computer and use it in GitHub Desktop.
002_linear_regression
# Calculate coefficients
b1 <- (sum((x - mean(x)) * (y - mean(y)))) / (sum((x - mean(x))^2))
b0 <- mean(y) - b1 * mean(x)
# Define function for generating predictions
simple_lr_predict <- function(x) {
return(b0 + b1 * x)
}
# Apply simple_lr_predict() to input data
simple_lr_predictions <- sapply(x, simple_lr_predict)
simple_lr_data$yhat <- simple_lr_predictions
# Visualize input data and the best fit line
ggplot(data = simple_lr_data, aes(x = x, y = y)) +
geom_point(size = 3, color = "#0099f9") +
geom_line(aes(x = x, y = yhat), size = 2) +
theme_classic() +
labs(
title = "Applying simple linear regression to data",
subtitle = "Black line = best fit line"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment