2017-10-06 149 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! –