Created
December 22, 2020 09:24
-
-
Save darioappsilon/fb7b8fe2e0c973c40ac68f35317efe5b to your computer and use it in GitHub Desktop.
002_linear_regression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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