require(ggplot2)
#have random normal distributions with means of 2 and 5, respectively.
n <- 20
df = data.frame(id=1:n, x=rnorm(n, mean=2, sd=.5), y=rnorm(n, mean=5, sd=2),
age=rnorm(n, mean = 40, sd = 30), female=sample(c(TRUE, FALSE), n, rep = TRUE) )
mod = lm(y ~ x, data=df)
summary(mod)
ggplot(df, aes(x=x, y=y)) + geom_point()
ggplot(df, aes(x=x, y=y)) + geom_point() +
geom_abline(intercept=mod$coefficients[1], slope=mod$coefficients[2]) +
stat_smooth()
# centering
mod = lm(center(y) ~ center(x), data=df)
summary(mod)
# center and z-score: (x - xbar)/sd(x)
# mod = lm(rescale(center(y)) ~ rescale(center(x)), data=df)
# as.beta(mod) # after fitting
with(df, center(y, as.factor(female))) # center by group
Run the code above in your browser using DataLab