Skip to content

Instantly share code, notes, and snippets.

@zdealveindy
Created April 25, 2022 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zdealveindy/8efc41433a4994608ee6283456f07d9f to your computer and use it in GitHub Desktop.
Save zdealveindy/8efc41433a4994608ee6283456f07d9f to your computer and use it in GitHub Desktop.
multi_reg
# Individual examples
# 1) Both w1 and w2 similarly related to y
set.seed (1234)
# Generate two random variables N(0,1)
x1 <- rnorm (100, 0, 1)
x2 <- rnorm (100, 0, 1)
X <- cbind (x1, x2)
# Generate correlation matrix to make variables correlated at r = 0.8
R <- matrix (c(sqrt (.8), sqrt (.2), sqrt (0.2), sqrt (.8)), ncol = 2)
W <- X%*%R
W <- data.frame (W)
names (W) <- c('w1', 'w2')
y <- W$w1 + W$w2 + rnorm (100, mean = 0, sd = 2)
# Calculate regression of y on x1, x2 and x1 + x2 (standard regression coefficients)
summary (lm (scale (y) ~ scale (w1) - 1, data = W))
summary (lm (scale (y) ~ scale (w2) - 1, data = W))
summary (lm (scale (y) ~ scale (w1) + scale (w2) - 1, data = W))
# 2) Situation that w2 is a bit more strongly related to y than w2
set.seed (1239)
# Generate two random variables N(0,1)
x1 <- rnorm (100, 0, 1)
x2 <- rnorm (100, 0, 1)
X <- cbind (x1, x2)
# Generate correlation matrix to make variables correlated at r = 0.8
R <- matrix (c(sqrt (.8), sqrt (.2), sqrt (0.2), sqrt (.8)), ncol = 2)
W <- X%*%R
W <- data.frame (W)
names (W) <- c('w1', 'w2')
y <- W$w1 + W$w2 + rnorm (100, mean = 0, sd = 2)
# Calculate regression of y on x1, x2 and x1 + x2 (standard regression coefficients)
summary (lm (scale (y) ~ scale (w1) - 1, data = W))
summary (lm (scale (y) ~ scale (w2) - 1, data = W))
summary (lm (scale (y) ~ scale (w1) + scale (w2) - 1, data = W))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment