2016-01-17 100 views
2

我具有导致一台状输出下面的代码保存输出为.csv表

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的任何建议?

+0

是你想写在“key:value”形式的东西吗? 'write.csv'根据错误期望data.frame,所以你将不得不将结果按照它可以采取的方式处理。 – steveb

+0

只是为了澄清,你将不得不采取'confusionMatrix'的结果,并把你需要的数据放到data.frame中。 – steveb

+0

@steveb是的,我现在看到。 mroto在下面的回应中非常清楚地概述了它。 – Oposum

回答

2

好了,如果你检查的confusionMatrix(xtab, prevalence = 0.25)输出,这是一个列表:

cm <- confusionMatrix(pred, truth) 
str(cm) 

    List of 5 
$ positive: chr "abnormal" 
$ table : 'table' int [1:2, 1:2] 231 27 32 54 
    ..- attr(*, "dimnames")=List of 2 
    .. ..$ Prediction: chr [1:2] "abnormal" "normal" 
    .. ..$ Reference : chr [1:2] "abnormal" "normal" 
$ overall : Named num [1:7] 0.828 0.534 0.784 0.867 0.75 ... 
    ..- attr(*, "names")= chr [1:7] "Accuracy" "Kappa" "AccuracyLower" "AccuracyUpper" ... 
$ byClass : Named num [1:8] 0.895 0.628 0.878 0.667 0.75 ... 
    ..- attr(*, "names")= chr [1:8] "Sensitivity" "Specificity" "Pos Pred Value" "Neg Pred Value" ... 
$ dots : list() 
- attr(*, "class")= chr "confusionMatrix" 

从这里开始,你选择要创建从CSV并作出data.frame将在适当的对象每个变量都有一列。在你的情况下,这将是:

tocsv <- data.frame(cbind(t(cm$overall),t(cm$byClass))) 

# You can then use 
write.csv(tocsv,file="file.csv") 
+0

谢谢,这非常接近。实际上,我稍微改变了你的代码以得到我想要的:'tocsv <-as.data.frame(t(data.frame(cbind(t(cm $ byClass),t(cm $ overall)))))''但是,如果我可以问你,为什么你首先要转位呢?另外,在我们进入'tocsv'阶段之前,是否需要将数值舍入?我后来知道,我可以命名该专栏,围绕它,然后替换它,但我想知道在初始阶段是否有更有效的方法。 – Oposum

+0

另外我注意到代码改变了原始行'95%CI:(0.7844,0.8668)',而是显示了这两行:'AccuracyLower 0.7844134380'和'AccuracyUpper 0.8667985207'。有没有办法保持原始方式'95%CI:(0.7844,0.8668)'? – Oposum

+1

默认情况下'byClass'和'overall'是命名的数值向量,它们不能以当前形式结合在一起。如果转置它们,则会在值的旁边创建名称的字符向量。至于将它们四舍五入,可能是的,但是如果你有一个问题,通常是好的做法,而不是在评论中填充它们。 – mtoto