r - 禁止在 tableGrob 中显示 "NA"

标签 r ggplot2

我有一个表格,我想使用 tableGrob 将其与 ggplot2 图一起绘制。出于输出目的,我想禁止打印 NA。

示例:

library(RGraphics) # support of the "R graphics" book, on CRAN
library(gridExtra) 

tab <- head(iris)
tab[1,2] <- NA # set a couple values to NA for example purposes
g1 <- tableGrob(tab)

#"Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
g2 <- qplot(Sepal.Length,  Petal.Length, data=iris, colour=Species)
grid.arrange(g1, g2, ncol=1, main="The iris data")

enter image description here

最佳答案

您正在绘制的数据表存储在元素g1$d中。

 g1$d
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1          NA          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

由于仅将 NA 替换为 "" 会将列转换为字符和松散格式,因此首先应将数据框列转换为字符,然后 NA 值被替换,数据结构转换回数据框架(以除去引号)。

g1$d<-apply(g1$d,2,as.character)
g1$d[is.na(g1$d)]<-""
g1$d<-as.data.frame(g1$d)
g1$d
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1                      1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

grid.arrange(g1, g2, ncol=1, main="The iris data")

enter image description here

关于r - 禁止在 tableGrob 中显示 "NA",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15097529/

相关文章:

r - 四开演示文稿的默认字体是什么?

R For循环删除从一个字符串到列中第二个字符串的行范围

r - 如何对排名数据建模

r - 从润滑日期时间对象中提取时间(HMS)?

r - 使用 ggplot2 中的 facet_grid 更改中断次数

r - 在ggplot2中添加图例

r - 不因式分解 x 轴标签的因素

r - 如何使用 Google Analytics (rga) 编写动态报告

r - 如何绘制以 x 轴为因子的平滑线 (ggalt::xspline) 图

r - 在 R 中使用 ggplot() 时编写手动图例