Skip to content

Instantly share code, notes, and snippets.

@Laurae2
Last active February 24, 2017 19:02
Show Gist options
  • Save Laurae2/b338b60ea3f01c3a72be7e54ae032a9e to your computer and use it in GitHub Desktop.
Save Laurae2/b338b60ea3f01c3a72be7e54ae032a9e to your computer and use it in GitHub Desktop.
Linear Regression demo using R
# Setting up random matrix
data <- as.matrix(data.frame(Intercept = rep(1, 6),
a = c(3, 4, 5, 6, 7, 8),
b = c(1, 4, 3, 7, 10, 12),
c = c(6, 5, 1, 9, 18, 21)))
# Setting up the (perfect) linear relationship
preds <- 2 + (data[, 2] * 2) + (data[, 3] * 3) + (data[, 4] * 4)
# Plotting data to understand what we have
PerformanceAnalytics::chart.Correlation(data.frame(data, preds = preds))
# If you do not have PerformanceAnalytics package, use this instead
# plot(data.frame(data, preds = preds))
# Getting linear regression coefficients
coefficients <- solve(t(data) %*% data, tol = 1e-30) %*% t(data) %*% preds
# Predicting on data
data %*% coefficients
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment