r - 将 fusionMatrix 的输出保存为 .csv 表

标签 r csv export-to-csv confusion-matrix

我有以下代码,产生类似表格的输出

 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)

 library(caret)
 confusionMatrix(xtab)

 confusionMatrix(pred, truth)
 confusionMatrix(xtab, prevalence = 0.25)   

我想将输出的以下部分导出为 .csv

               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  

尝试将其写入 .csv 表会导致错误消息:

write.csv(confusionMatrix(xtab),file="file.csv")
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
cannot coerce class ""confusionMatrix"" to a data.frame

由于显而易见的原因,手动完成整个工作是不切实际的,并且容易出现人为错误。

有关如何将其导出为 .csv 的任何建议吗?

最佳答案

使用插入符包

results <- confusionMatrix(pred, truth)

as.table(结果) 给出

         Reference
Prediction  X1  X0
        X1  36  29
        X0 218 727

as.matrix(results,what="overall") 给出

Accuracy       7.554455e-01
Kappa          1.372895e-01
AccuracyLower  7.277208e-01
AccuracyUpper  7.816725e-01
AccuracyNull   7.485149e-01
AccuracyPValue 3.203599e-01
McnemarPValue  5.608817e-33

as.matrix(results, What = "classes") 给出

Sensitivity          0.8953488
Specificity          0.6279070
Pos Pred Value       0.8783270
Neg Pred Value       0.6666667
Precision            0.8783270
Recall               0.8953488
F1                   0.8867562
Prevalence           0.7500000
Detection Rate       0.6715116
Detection Prevalence 0.7645349
Balanced Accuracy    0.7616279

使用这些和 write.csv 命令,您可以获得整个混淆矩阵信息

关于r - 将 fusionMatrix 的输出保存为 .csv 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34842837/

相关文章:

PHP和SQL带来不同的结果

python - 使用 Zip 函数在 CSV 中创建数据长度不同的列

python - Pandas csv 到 psql : additional column is being generated in output (? )

android - 如何使用 Athena 从 AWS S3 上的隐藏 csv 文件(以点开头)查询数据

Java Servlet 将表单输入写入 CSV

r - OR 运算符作为功能开关

R、knitr、xtable、交替行颜色

r - 如何删除 ggplot geom_bar 图中的选择标签并将这些标签居中?

r - 如何在函数中使用 Dplyr::Rename_At 和 "Starts_with"

Python:计算 CSV 中每小时的平均值?