对数据框的多变量数据,进行 regression analysis时,经常需要对每个变量分别做regression 分析。需要写一个loop,实现办法就是,先构建好formula的字符串,然后使用as.formula()
函数将字符串转化成formula即可在拟合函数中使用,比如 lm()函数。
解决办法
as.formula()
函数是关键。
A slightly different approach is to create your formula from a string. In the formula help page you will find the following example :
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))
This works very well for reading these values from a file.
参考
How to succinctly write a formula with many variables from a data frame?