Home > Software engineering >  Saving output of a confusion matrix to a dataframe in R
Saving output of a confusion matrix to a dataframe in R

Time:04-09

In R, I'm creating two separate confusion matrices and would like to write the results of each to a data frame. Here is the setup:

library(caret)

Confusion Matrix 1

lvs_1 <- c("normal", "abnormal")
truth_1 <- factor(rep(lvs_1, times = c(86, 258)),
                levels = rev(lvs_1))
pred_1 <- factor(
  c(
    rep(lvs_1, times = c(54, 32)),
    rep(lvs_1, times = c(27, 231))),               
  levels = rev(lvs_1))

xtab_1 <- table(pred_1, truth_1)

Now, I create the confusion matrix:

foo <- confusionMatrix(xtab_1)

I would like to save the results for Accuracy, Specificity, and Sensitivity stored in foo to a data frame df:

foo$overall[['Accuracy']]
foo$byClass[['Specificity']]
foo$byClass[['Sensitivity']]

df would look as follows:

              Accuracy   Specificity    Sensitivity
matrix_1      0.8284884  0.627907       0.8953488

Next, I create another confusion matrix. The setup:

Confusion Matrix 2

lvs_2 <- c("normal", "abnormal")
truth_2 <- factor(rep(lvs_2, times = c(75, 269)),
                  levels = rev(lvs_2))
pred_2 <- factor(
  c(
    rep(lvs_2, times = c(44, 42)),
    rep(lvs_2, times = c(37, 221))),               
  levels = rev(lvs_2))

xtab_2 <- table(pred_2, truth_2)

The confusion matrix is:

bar <- confusionMatrix(xtab_2)

I would like to be able to write the results of bar to df

bar$overall[['Accuracy']]      #0.8023256
bar$byClass[['Specificity']]   #0.5866667
bar$byClass[['Sensitivity']]   #0.8624535

The final df would look as follows:

              Accuracy     Specificity    Sensitivity
matrix_1      0.8284884    0.627907       0.8953488
matrix_2      0.8023256    0.5866667      0.8624535

What is the best way to do this?

Thanks!

CodePudding user response:

This should do it:

Accuracy <- c(foo$overall[['Accuracy']] , bar$overall[['Accuracy']])
Specificity <- c(foo$overall[['Specificity']] , bar$overall[['Specificity']])
Sensitivity <- c(foo$overall[['Sensitvity']] , bar$overall[['Sensitvity']])
df <- data.frame(Accuracy, Specificity, Sensitivity)

Or create separate df's for each matrix and use rbind to combine them.

  • Related