问题
I'm trying to fit several models in R using the for loop.
The data I want to fit is the classical Auto data in a R pre-build package. Let's discover the names of the columns of this dataframe:
names(Auto)
"mpg" "cylinders" "displacement" "horsepower" "weight" "acceleration" "year"
"origin" "name"
I want to fit the all these predictors one by one with the target 'mpg'.
Instead of doing:
autotest1 = lm(mpg~cylinders, data=Auto)
autotest2 = lm(mpg~displacement, data=Auto)
autotest3 = lm(mpg~horsepower, data=Auto)
autotest4 = lm(mpg~weight, data=Auto)
autotest5 = lm(mpg~acceleration, data=Auto)
autotest6 = lm(mpg~year, data=Auto)
autotest7 = lm(mpg~origin, data=Auto)
I'm trying to use the for loop:
for (var in names(Auto))
{
cat(lm(mpg~var, data=Auto))
}
Error in model.frame.default(formula = mpg ~ var, data = Auto, drop.unused.levels = TRUE) :
variable lengths differ (found for 'var')
I'm also trying Auto[i] with the index i being the columns of Auto dataframe without any success. Anyone could help me?
回答1:
We can create a formula object with paste
for(var in names(Auto)) print(lm(paste('mpg ~', var), data = Auto))
Or with reformulate
for(var in names(Auto)) print(lm(reformulate(var, 'mpg'), data = Auto))
回答2:
Another option would be something like:
Auto <- mtcars
Auto$Var <- 1
Temp <- list()
for (i in 2:c(length(names(Auto))-1)) {
print(names(Auto)[i])
Auto$Var <- Auto[,i]
ModelTemp <- lm(mpg~Var, data=Auto)
Temp[[i-1]] <- ModelTemp
}
来源:https://stackoverflow.com/questions/62363528/how-to-use-for-in-the-dataframes-in-r-programming