这是一种方法的演示。更复杂的实现可能会更新拟合的线性模型(请参阅 参考资料?update
),但这超出了您的问题的直接范围。
## Make a reproducible example!!
df <-
setNames(as.data.frame(matrix(rnorm(96), ncol=8)),
c("MRPCM1","MRPCM2","MRPCM3","DSEX","IEP", "ELL3","SDRACEM","PARED"))
## Construct a template formula
f <- MRPCM ~ DSEX + IEP + ELL3 + SDRACEM + PARED
## Workhorse function
iterlm <- function(formula, data) {
## Find columns in data matching pattern on left hand side of formula
LHSpat <- deparse(formula[[2]])
LHSvars <- grep(LHSpat, names(data), value = TRUE)
## Run through matchded columns, repeatedly updating the formula,
## fitting linear model, and extracting whatever results you want.
sapply(LHSvars, FUN=function(var) {
uf <- update.formula(f, as.formula(paste(var, "~ .")))
coef(lm(uf, df))
})
}
## Try it
iterlm(f, df)
## MRPCM1 MRPCM2 MRPCM3
## (Intercept) 0.71638942 -0.3883355 0.22202700
## DSEX -0.07048994 -0.7478064 0.62590580
## IEP -0.22716821 -0.2381982 0.12205780
## ELL3 -0.44492392 0.1720344 0.41251561
## SDRACEM 0.21629235 0.4800773 0.02866802
## PARED 0.07885683 -0.2582598 -0.07996121