首页 > 解决方案 > R 有光泽;在渲染中全局定义 NA 行为

问题描述

在制作包含许多包含一些 NA 值的表的 Shiny 应用程序时,全局定义 NA 的打印方式可能会有所帮助,例如renderTable.

举个例子:

library(shiny)
ui <- fluidPage(
  column(2,uiOutput("ourTable")),
  column(2,uiOutput("ourTable2"))
)

server <- function(input, output) {
  data<-data.frame(A=1:6, B=LETTERS[11:16], C=c(1,2,"A", "B", NA, NA))
  output$ourTable<-renderTable({data})
  output$ourTable2<-renderTable({data}, na="")
}

shinyApp(ui = ui, server = server)

这呈现如下:

在此处输入图像描述

理想情况下,我想添加一行代码(在服务器中或在 ui 中),以便所有表都呈现为ourTable2,也就是说,无需NA在输出中打印,也无需为我添加的每个表明确指定这一点。

标签: rshinyna

解决方案


如果您愿意,可以在 global.R 文件(或 server.R)文件中定义以下内容。如果整个表为 NA,这将适用于您的表并返回“”。如果您传递复杂的对象,例如嵌入式列表列表,则需要更复杂一些。但是,在 OP 中打印 data.frame 将起作用。

在 global.R (或其他地方):

format.NAs <- function(x) {
  if (identical(x,NA)) return ("")
  x <- as.data.frame(lapply(df,unclass)) #to accommodate factors()
  x[is.na(x)] <- ""
  return (x)
}

在您的 server.r (或 UI 模块或需要的地方)

 output$ourTable2<-renderTable({format.NAs(data)})

一个通用的例子:

df <- data.frame(A=c(2,4,6,8),B=c(1,NA,9,7),C=c("test",NA,"test1",NA),stringsAsFactors = F)
> format.NAs(df)
  A B     C
1 2 1  test
2 4        
3 6 9 test1
4 8 7      

推荐阅读