Error in contrasts can be applied only to factors with 2 or more levels

本文详细解释了如何在R中遇到'contrastscanbeappliedonlytofactorswith2ormorelevels'错误,原因在于变量var2只有唯一值。解决办法是移除该变量并重新构建回归模型,展示了相关代码及模型调整后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]): contrasts can be applied only to factors with 2 or more levels

目录

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?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Data+Science+Insight

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值