Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]): contrasts can be applied only to factors with 2 or more levels
目录
问题:
var2变量的内容全是4;
只有一个独特值(unique);
#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
var2=as.factor(4),
var3=c(7, 7, 8, 3, 2),
var4=c(1, 1, 2, 8, 9))
#view data frame
df
#attempt to fit regression model
model <- lm(var4 ~ var1 + var2 + var3, data=df)
解决:
#剔除var2之后再构建回归模型;
#fit regression model without using var2 as a predictor variable
model <- lm(var4 ~ var1 + var3, data=df)
#view model summary
summary(model)
Call:
lm(formula = var4 ~ var1 + var3, data = df)
Residuals:
1 2 3 4 5
0.02326 -1.23256 0.91860 0.53488 -0.24419
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.4070 3.6317 2.315 0.1466
var1 0.6279 0.6191 1.014 0.4172
var3 -1.1512 0.3399 -3.387 0.0772 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.164 on 2 degrees of freedom
Multiple R-squared: 0.9569, Adjusted R-squared: 0.9137
F-statistic: 22.18 on 2 and 2 DF, p-value: 0.04314
完整错误:
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]): contrasts can be applied only to factors with 2 or more levels Traceback: 1. lm(var4 ~ var1 + var2 + var3, data = df) 2. model.matrix(mt, mf, contrasts) 3. model.matrix.default(mt, mf, contrasts) 4. `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) 5. stop("contrasts can be applied only to factors with 2 or more levels")
参考:How to Fix: contrasts can be applied only to factors with 2 or more levels
参考:R
参考:回归模型
参考:https://stackoverflow.com/questions/44200195/how-to-debug-contrasts-can-be-applied-only-to-factors-with-2-or-more-levels-er
How to debug "contrasts can be applied only to factors with 2 or more levels" error?