[英]How to create the confusion matrix with stargazer and caret
我正在尝试在sweave r中创建一个表,但它并没有按我的意愿出来。 这是我的代码。
<<results='asis'>>=
## 2 class example
library(caret)
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
levels = rev(lvs))
pred <- factor(c(rep(lvs, times = c(54, 32)),
rep(lvs, times = c(27, 231))),
levels = rev(lvs))
xtab <- table(pred, truth)
Con.Mat <- confusionMatrix(xtab)
Con.Mat$table
Con.Mat$overall
Con.Mat$byClass
stargazer::stargazer(Con.Mat$table,head=FALSE,title = "Table")
stargazer::stargazer(Con.Mat$overall,head=FALSE,title = "overall")
stargazer::stargazer(Con.Mat$byClass,head=FALSE,title = "byClass")
@
带有confusionMatrix()函数的R的输出如下
> confusionMatrix(xtab)
Confusion Matrix and Statistics
truth
pred abnormal normal
abnormal 231 32
normal 27 54
Accuracy : 0.8285
95% CI : (0.7844, 0.8668)
No Information Rate : 0.75
P-Value [Acc > NIR] : 0.0003097
Kappa : 0.5336
Mcnemar's Test P-Value : 0.6025370
Sensitivity : 0.8953
Specificity : 0.6279
Pos Pred Value : 0.8783
Neg Pred Value : 0.6667
Prevalence : 0.7500
Detection Rate : 0.6715
Detection Prevalence : 0.7645
Balanced Accuracy : 0.7616
'Positive' Class : abnormal
使用观星台时,请在此处输入图片说明
我遇到了同样的问题,发现以下解决方法:
1)首先,您必须使用as.data.frame.matrix()将混淆矩阵从类表转换为数据框。
ConfMat <- as.data.frame.matrix(Con.Mat$table)
2)然后,您可以使用摘要= FALSE参数,强制Stargazer将其输出生成为数据框。
stargazer(ConfMat, head = FALSE, title = "Table", summary = FALSE)
以后,您可以通过在数据框中创建列或行总计来添加列或行。 另外,在中间的行之间添加百分比。
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.