2017-10-06 105 views
1

[R] 我有一張表波士頓有14個定量預測指標。我想使用poly函數遍歷所有的預測變量。 單獨使用每個預測工作,例如。 lm(crim~poly(nox,3))多功能變量在數據幀中的多功能用法

遇到問題通過的所有預測循環: 我嘗試使用,

colnames(Boston) = > 
[1] "crim" "zn"  "indus" "chas" "nox"  "rm"  "age"... 

for(index in colnames(Boston)){ 
    lm(crim~poly(index,3)) 
} 

我得到的錯誤:在聚 錯誤(A =指數,3): '度' 必須小於獨特點的數量

是否有任何其他方式在循環中正確引用索引中的變量名?

回答

0

下面的循環對我的作品,但是應該降低度(多項式)的情況下,所述唯一的(列)的點的長度是小於3,

data(Boston) 

nams = colnames(Boston)[-1] 

for (i in nams) { 

    cat(i, " ", length(unique(Boston[, i])), '\n') 

    degree = 3 

    if (length(unique(Boston[, i])) < degree) { 

    degree = length(unique(Boston[, i])) - 1 
    } 

    tmp_formula = as.formula(paste(c('crim ~ poly(', i, ",", degree, ")"), collapse = "")) 

    print(tmp_formula) 

    fit = lm(tmp_formula, data = Boston) 
} 

示例輸出:

zn 26 
crim ~ poly(zn, 3) 
indus 76 
crim ~ poly(indus, 3) 
chas 2 
crim ~ poly(chas, 1) 
nox 81 
crim ~ poly(nox, 3) 
rm 446 
crim ~ poly(rm, 3) 
age 356 
crim ~ poly(age, 3) 
dis 412 
crim ~ poly(dis, 3) 
rad 9 
crim ~ poly(rad, 3) 
tax 66 
crim ~ poly(tax, 3) 
ptratio 46 
crim ~ poly(ptratio, 3) 
black 357 
crim ~ poly(black, 3) 
lstat 455 
crim ~ poly(lstat, 3) 
medv 229 
crim ~ poly(medv, 3) 
+0

謝謝@lampros! –