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

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

top.table <- structure(c(7,8,10,11,12,13,14,15,16,17,18,57.5,45.5,NA,128.5,78.5,71.5,49,1043,710,838,1481,737,1096,5923,3697,1726,3545,1733,2333,3807,1795,2761,2887,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)    
iCMS 回答:删除NA,仅填充tableGrob中包含数字的单元格

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

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

grid.newpage()
grid.draw(g) 

enter image description here

,

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

#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,theme = tt1)

grid.draw(g)
本文链接:https://www.f2er.com/1968537.html

大家都在问