问题
Based on the answers of this question, I tried to write the following codes:
for(var in names(Auto)) {print(var)}
"mpg" [1] "cylinders" [1] "displacement" [1] "horsepower" [1] "weight" [1] "acceleration" [1] "year" [1] "origin"
Ok, my name variables are in names(Auto), then I moved on:
for(var in names(Auto))
{
summary(lm(paste('mpg ~', var), data = Auto))
}
Warning messages:
1: In model.matrix.default(mt, mf, contrasts) :
the response appeared on the right-hand side and was dropped
2: In model.matrix.default(mt, mf, contrasts) :
problem with term 1 in model.matrix: no columns are assigned
Strangely for one iteration we have:
var='cylinders'
summary(lm(paste('mpg ~', var), data = Auto)
Call:
lm(formula = paste("mpg ~", var), data = Auto)
Residuals:
Min 1Q Median 3Q Max
-14.2413 -3.1832 -0.6332 2.5491 17.9168
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 42.9155 0.8349 51.40 <2e-16 ***
cylinders -3.5581 0.1457 -24.43 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 4.914 on 390 degrees of freedom
Multiple R-squared: 0.6047, Adjusted R-squared: 0.6037
F-statistic: 596.6 on 1 and 390 DF, p-value: < 2.2e-16
That's what I wanted for each iteration.
来源:https://stackoverflow.com/questions/62364671/strange-for-loop-behavior-on-r-programming