[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))
}
我收到错误: poly(A = index,3)出错: 'degree'必须小于唯一点的数量
还有其他方法可以在循环中正确引用索引中的变量名吗?
答案 0 :(得分: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)