将混淆矩阵的输出保存到 R 中的数据帧
Saving output of a confusion matrix to a dataframe in R
在 R 中,我正在创建两个单独的混淆矩阵,并希望将每个矩阵的结果写入数据框。这是设置:
library(caret)
混淆矩阵 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)
现在,我创建混淆矩阵:
foo <- confusionMatrix(xtab_1)
我想将存储在 foo
中的准确性、特异性和灵敏度的结果保存到数据框 df
:
foo$overall[['Accuracy']]
foo$byClass[['Specificity']]
foo$byClass[['Sensitivity']]
df
将如下所示:
Accuracy Specificity Sensitivity
matrix_1 0.8284884 0.627907 0.8953488
接下来,我创建另一个混淆矩阵。设置:
混淆矩阵 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)
混淆矩阵为:
bar <- confusionMatrix(xtab_2)
我希望能够将 bar
的结果写入 df
bar$overall[['Accuracy']] #0.8023256
bar$byClass[['Specificity']] #0.5866667
bar$byClass[['Sensitivity']] #0.8624535
最终的 df
如下所示:
Accuracy Specificity Sensitivity
matrix_1 0.8284884 0.627907 0.8953488
matrix_2 0.8023256 0.5866667 0.8624535
最好的方法是什么?
谢谢!
应该这样做:
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)
或者为每个矩阵创建单独的 df,然后使用 rbind
组合它们。
在 R 中,我正在创建两个单独的混淆矩阵,并希望将每个矩阵的结果写入数据框。这是设置:
library(caret)
混淆矩阵 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)
现在,我创建混淆矩阵:
foo <- confusionMatrix(xtab_1)
我想将存储在 foo
中的准确性、特异性和灵敏度的结果保存到数据框 df
:
foo$overall[['Accuracy']]
foo$byClass[['Specificity']]
foo$byClass[['Sensitivity']]
df
将如下所示:
Accuracy Specificity Sensitivity
matrix_1 0.8284884 0.627907 0.8953488
接下来,我创建另一个混淆矩阵。设置:
混淆矩阵 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)
混淆矩阵为:
bar <- confusionMatrix(xtab_2)
我希望能够将 bar
的结果写入 df
bar$overall[['Accuracy']] #0.8023256
bar$byClass[['Specificity']] #0.5866667
bar$byClass[['Sensitivity']] #0.8624535
最终的 df
如下所示:
Accuracy Specificity Sensitivity
matrix_1 0.8284884 0.627907 0.8953488
matrix_2 0.8023256 0.5866667 0.8624535
最好的方法是什么?
谢谢!
应该这样做:
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)
或者为每个矩阵创建单独的 df,然后使用 rbind
组合它们。