【发布时间】:2019-08-23 17:09:41
【问题描述】:
我目前正在对一系列因变量(几乎 200 个)执行多元线性回归分析,并希望创建一个函数,为一组指定的列运行此函数,然后提取相关模型估计值,例如Beta 系数和 p 值。
模拟数据:
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')))
看起来像:
ID age sex testscore_1 testscore_2 testscore_3 education
1 1001 56 0 23 1 18 5
2 1002 43 1 28 3 20 4
3 1003 59 0 30 2 19 3
4 1004 74 0 15 5 15 5
5 1005 61 1 7 8 20 2
6 1006 62 1 18 2 23 1
7 1007 69 0 29 5 19 4
8 1008 80 1 27 6 25 4
9 1009 40 0 14 7 10 3
10 1010 55 1 22 8 14 5
11 1011 58 0 24 2 12 2
我正处于一个功能可行的阶段:
lm_results <- lapply(df[,4:6], function(x) lm(x ~ age + sex + education,
data = df))
我可以从中得出系数估计:
Coefficient <- data.frame(coefficients = sapply(lm_results, getElement, name = "coefficients"))
它返回每个testscore_*变量中每个预测变量的系数,尽管我无法从中得出p值 这些模型:
P_values <- data.frame(p.values = sapply(lm_results, getElement, name = "qr"))
有人有解决这个问题的建议吗?
【问题讨论】:
标签: r function regression linear-regression