## Calculate semi-partial and partial R2 values in a bivariate ## regression setting while systematically varying the correlation ## between the two covariates. ## Sample size. n = 100 M = NULL for (r in seq(-0.9, 0.9, 0.1)) { sp_r2 = NULL p_r2 = NULL ## Do replications to get a more stable result. for (k in 1:100) { ## Generate the design matrix. X1 = rnorm(n) U = rnorm(n) X2 = r*X1 + sqrt(1-r^2)*U X = cbind(X1, X2) ## Simulate the response. Y = X1 + X2 + rnorm(n) ## Calculate the full model R^2. m_full = lm(Y ~ X) R2_full = cor(Y, m_full$fitted.values)^2 ## Calculate the submodel R^2 for X2 only. m_2 = lm(Y ~ X2) R2_2 = cor(Y, m_2$fitted.values)^2 ## The semi-partial and partial R^2. sp_r2[k] = R2_full- R2_2 p_r2[k] = sp_r2[k]/(1-R2_2) } M = rbind(M, c(r, mean(sp_r2), mean(p_r2))) }