删除 NA 并仅填充 tableGrob 中包含数字的单元格

Remove NA and only fill cells containing numbers in tableGrob

我有一个 table (top.table),我想在 ggplot 中显示,但在重新格式化 table 时遇到问题。我需要对其进行格式化,使所有 NA 元素均为空白,并且仅在元素中包含数字时才填充指定的颜色。基本上,像下面的代码一样填充颜色,除了 NA 元素应该默认填充(白色),并且 NA 文本应该被删除。如果无法按照我描述的方式删除 NA,更改文本 color/fill 也对我有用(即更改文本 color/fill 的数字,但不更改 NA)。

top.table <- structure(c(7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 57.5, 45.5, 
NA, NA, NA, 128.5, 78.5, 71.5, 49, NA, NA, NA, 1043, NA, NA, 
710, 838, 1481, 737, NA, NA, 1096, 5923, 3697, NA, 1726, NA, 
NA, 3545, NA, NA, 1733, 2333, NA, 3807, 1795, NA, 2761, NA, 2887, 
NA, NA, 2211, 2544), .Dim = c(11L, 5L), .Dimnames = list(NULL, 
    c("Sample Number", "Static", "D10 FB", "D12 FB", "D14 FB"
    )))

colors <- structure(list(newcolor = c("dodgerblue2", "#E31A1C", "#FDBF6F", 
"palegreen2", "skyblue2", "green4", "#6A3D9A", "#FF7F00", "gold1", 
"#CAB2D6", "#FB9A99")), row.names = c(NA, -11L), class = c("tbl_df", 
"tbl", "data.frame"))

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = colors, col = NA))
)

g <- tableGrob(top.table, theme = tt1)
grid.draw(g)    

这似乎是一个非常明显的解决方案,但为什么不在绘制 table 时将 NA 替换为空字符串呢?

g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.newpage()
grid.draw(g) 

在@AllanCameron 的帮助下,我想出的解决方案是使用重复颜色到 top.table 中的列数,并在调用之前使用 replace() 将所有 NA 元素转换为“白色” tableGrob()

#make repeated columns of colors
table.colors <- matrix(rep(colors, each = ncol(top.table)), 
                       ncol = ncol(top.table), byrow = TRUE)

#index matrix to fine NAs
table.ind <- is.na(top.table)

#make replacements
table.colors <- replace(table.colors, table.ind, "white")

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = table.colors))
)

g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.draw(g)