我有机器学习模型的混淆矩阵结果,我需要展示这些结果。我使用Microsoft Word手动制作了如下图所示的表格。可以看到,这个表格看起来并不美观,更重要的是,将结果从R转移到Microsoft Word并手动计算错误需要花费大量时间。
由于我的大部分分析将在R中完成,因此我想使用R生成这个表格。我也非常乐意听取您的建议,使其更加美观,因为我将在科学演讲中使用这个表格。
为了可重复性,我使用了代码dput(cm_df)(这是我的混淆矩阵转换为数据框,使用as.data.frame(cm_table)),得到了以下结果:
structure(list(Prediction = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), Reference = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), Freq = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 9L, 0L, 0L, 1L, 0L, 1L, 2L, 12L, 1L, 2L, 0L, 0L, 4L, 1L, 0L, 1L, 1L, 0L, 7L, 1L, 0L, 15L, 0L, 0L, 0L, 2L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, -36L))
有什么想法吗?
回答:
有许多用于格式化表格的选项和包,它们提供不同的输出格式(例如markdown、html、pdf、docx等)。这里是一个使用huxtable
包的示例:
library(data.table)library(huxtable)library(dplyr)# 重新格式化您的cm_df数据框res <- dcast(as.data.table(cm_df), Prediction ~ Reference, value.var = "Freq")# 提取数字矩阵以计算统计数据mat <- data.matrix(res[,-1])# 将res设置为字符类型(合并所需)res[] <- lapply(res, as.character)# 计算并格式化统计数据eoc <- (rowSums(mat) - diag(mat))/rowSums(mat)res[, `:=`(UA = paste0(round(100*(1-eoc)), "%"), `Error of Commission` = paste0(round(100*eoc), "%"))]PA <- paste0(round(100*diag(mat)/colSums(mat)), "%")EO <- paste0(round(100*(1-diag(mat)/colSums(mat))), "%")# 将列统计数据与res合并res.tab <- rbind(res, setNames(transpose(data.table(PA=PA, `Er. Omission`=EO), keep.names = "Prediction"), colnames(res)[1:7]), fill=TRUE)# 格式化表格out <- as_huxtable(res.tab) %>% set_bold(1, everywhere, TRUE) %>% set_bold(everywhere, 1, TRUE) %>% set_bottom_border(1, everywhere) %>% set_bottom_border(7, everywhere) %>% set_left_border(everywhere, c(2,8), TRUE) %>% set_align(1, everywhere, "center") %>% set_align(everywhere, 1, "center") %>% set_align(c(2:9), c(2:9), "right") %>% set_col_width(c(0.4, rep(0.2, 6), rep(.3,2))) %>% set_position("left")# 打印表格到屏幕上(通常会导出到首选格式)print_screen(out)#> Prediction │ 1 2 3 4 5 #> ───────────────┼────────────────────────────────#> 1 │ 1 1 1 0 0 #> 2 │ 0 9 2 4 7 #> 3 │ 0 0 12 1 1 #> 4 │ 0 0 1 0 0 #> 5 │ 0 1 2 1 15 #> 6 │ 0 0 0 1 0 #> ───────────────┼────────────────────────────────#> PA │ 100% 82% 67% 0% 65% #> Er. Omission │ 0% 18% 33% 100% 35% #> #> Column names: Prediction, 1, 2, 3, 4, 5, 6, UA, Error of Commission#> #> 6/9 columns shown.
编辑:
根据要求,您可以添加以下代码来获取一些注释:
# 添加一个空的第一列并合并单元格out <- merge_down(as_huxtable(cbind(rep("", 9), out)), 2:8, 1)# 添加所需的标签out[2,1] <- "Classification"# 添加顶部标题并旋转第一列的文本out %>% set_caption("Reference") %>% set_rotation(everywhere, 1, 90)
输出(html版本):