简体   繁体   English

如何用观星者和插入符号创建混淆矩阵

[英]How to create the confusion matrix with stargazer and caret

I'm trying to create a one table in sweave r, but it does not come out as I want. 我正在尝试在sweave r中创建一个表,但它并没有按我的意愿出来。 This is the code I have. 这是我的代码。

<<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")
@

The output of R with the confusionMatrix () function is as follows 带有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

While using stargazer enter image description here 使用观星台时,请在此处输入图片说明

I came across the same problem and found the following workaround: 我遇到了同样的问题,发现以下解决方法:

1) First you must convert the confusion matrix from class table to dataframe with as.data.frame.matrix(). 1)首先,您必须使用as.data.frame.matrix()将混淆矩阵从类表转换为数据框。

ConfMat <- as.data.frame.matrix(Con.Mat$table)

2) Then, you can force Stargazer to produce the output as a data frame, with summary = FALSE argument. 2)然后,您可以使用摘要= FALSE参数,强制Stargazer将其输出生成为数据框。

stargazer(ConfMat, head = FALSE, title = "Table", summary = FALSE)

Later, you can add columns or row total by creating them in the dataframe. 以后,您可以通过在数据框中创建列或行总计来添加列或行。 Also, add inbetween rows with percentages. 另外,在中间的行之间添加百分比。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM