问题
I want to improve the way to insert predictors in a regression function:
fm <- lm(formula= df$dependent_variable ~ df[,2] + df[,3]+ df[,4], data = df)
df = data.frame
In this example I put only 4 predictors and 1 dependent_variable. Actually I have 191 predictors. I think I need to a loop script to put all these predictors. Suggestions?
回答1:
Here is one possible solution:
yname<-"DVnamehere"
xnames<-colnames(dat)
xnames<-xnames[-which(xnames==yname)]
formula<-as.formula(paste(yname,"~",paste(xnames,collapse="+")))
model<-lm(formula,data=dat)
summary(model)
While this is not a loop it only requires you specify the name of the dependent variable, and uses the rest of the variables in the data set as the predictors then puts everything the regression formula. Does this help?
来源:https://stackoverflow.com/questions/31477059/loop-function-to-add-large-numbers-of-predictors-in-regression-function