【发布时间】:2019-10-04 20:55:19
【问题描述】:
我目前正在尝试运行一个循环,对具有多个因变量 (n=1000) 的多个自变量 (n = 6) 执行线性回归。
这是一些示例数据,年龄、性别和教育程度代表我感兴趣的自变量,而 testcore_* 是我的因变量。
df = data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006,1007, 1008, 1009, 1010, 1011),
age = as.numeric(c('56', '43','59','74','61','62','69','80','40','55','58')),
sex = as.numeric(c('0','1','0','0','1','1','0','1','0','1','0')),
testscore_1 = as.numeric(c('23','28','30','15','7','18','29','27','14','22','24')),
testscore_2 = as.numeric(c('1','3','2','5','8','2','5','6','7','8','2')),
testscore_3 = as.numeric(c('18','20','19','15','20','23','19','25','10','14','12')),
education = as.numeric(c('5','4','3','5','2', '1','4','4','3','5','2')))
我的工作代码允许我为多个 DV 运行回归模型(我敢肯定,更有经验的 R 用户会不喜欢它,因为它缺乏效率):
y <- as.matrix(df[4:6])
#model for age
lm_results <- lm(y ~ age, data = df)
write.csv((broom::tidy(lm_results)), "lm_results_age.csv")
regression_results <-broom::tidy(lm_results)
standardized_coefficients <- lm.beta(lm_results)
age_standardize_results <- coef(standardized_coefficients)
write.csv(age_standardize_results, "lm_results_age_standardized_coefficients.csv")
然后,我将通过手动将 age 替换为 sex 和 education 来重复这一切
有没有人有更优雅的方式来运行这个 - 例如,通过所有感兴趣的 IV(即年龄、性别和教育)的循环?
如果有人建议将broom::tidy(lm_results) 与lm.beta::lm.beta 中的标准化系数结合起来,即将标准化回归系数与主模型输出相结合,我们将不胜感激。
【问题讨论】:
标签: r loops linear-regression lapply purrr