R卡方检验误差:';x';和';y';必须至少有2个级别

R卡方检验误差:';x';和';y';必须至少有2个级别,r,chi-squared,R,Chi Squared,我想知道,当只做出了一个级别的预测时,是否有办法绕过这个错误: Error in stats::chisq.test(y[1:20], predictions[1:20]) : 'x' and 'y' must have at least 2 levels 当chisq.test中的所有预测都是相同级别/类别时,我得到了它(即使变量有两个级别(尽管两个级别都不存在) 测试数据: y <- as.factor(c(rep(1, 10), rep(0, 11))) prediction

我想知道,当只做出了一个级别的预测时,是否有办法绕过这个错误:

Error in stats::chisq.test(y[1:20], predictions[1:20]) : 
  'x' and 'y' must have at least 2 levels
chisq.test
中的所有预测都是相同级别/类别时,我得到了它(即使变量有两个级别(尽管两个级别都不存在)

测试数据:

y <- as.factor(c(rep(1, 10), rep(0, 11)))
predictions <- as.factor(c(rep(1, 20), 0))

# Works (with a warning). 
chisq <- stats::chisq.test(y, predictions)

# Does not work due to not having prediction of both factors. 
chisq <- stats::chisq.test(y[1:20], predictions[1:20])


y考虑改用Fisher精确检验

stats::fisher.test(y, predictions)

卡方检验的“经验法则”是,它希望预期的细胞计数为5或更多。Fisher's exact没有此限制,您可以在卡方检验适用的任何2x2表格上使用它。

Try
chisq.test(表(y[1:20],预测[1:20]))
。您将看到
X平方
NaN
p值
NA
。这是因为某些预期计数为零。@DarrenTsai一旦OP确认答案脱离主题,我将删除我的答案