Created
January 31, 2022 04:32
-
-
Save RamiKrispin/96b6dacb50f4de0a08605a87ba81255b to your computer and use it in GitHub Desktop.
Calculate the beta coefficients for linear regression
This file contains 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
#generate random numbers | |
set.seed(1234) | |
x1 <- rnorm(n = 1000, mean = 3, sd = 3) | |
x2 <- rnorm(n = 1000, mean = 0, sd = 1) | |
noise <- runif(n = 1000, min = 0, max = 1) | |
# Set formula | |
y <- 5 * x1 - 3 * x2 + noise | |
# Run regression | |
md <- lm(y ~ x1 + x2) | |
summary(md) | |
# Calculate the beta coefficients | |
# Extract the Xs coefficients | |
b <- summary(md)$coef[-1, 1] | |
# Calculate the SD for the Xs and Y | |
sx <- sapply(md$model[-1], sd) | |
sy <- sd(md$model[1][,1]) | |
# Calculate the beta coefficients | |
beta <- b * sx/sy | |
beta | |
# Alternatively use the lm.beta function from the QuantPsyc package | |
library(QuantPsyc) | |
lm.beta(md) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment