R闪亮;在渲染中全局定义 NA 行为

R shiny; globally define NA behaviour in renders

当使用许多 table 包含一些 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 中),以便所有 table 都像 ourTable2 一样呈现,也就是说,没有NA 被打印在输出中,而不必为我添加的每个 table 明确指定。

您可以根据需要在 global.R 文件(或 server.R)文件中定义以下内容。如果整个 table 是 NA,这将对你的 tables 和 return "" 起作用。如果您传递复杂的对象,如嵌入的列表列表,则需要更复杂一些。但是,像 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      

根据 Ricardo 的 ,我编写了以下包装器,它对所有呈现的表格都有效(但不是其他输出表格的方式):

renderTableNew<-function(x){renderTable({x}, na="")}

显然,这个 'trick' 可以用来定义 renderTable() 的更多参数,并且可以使用不同的参数创建多个这样的函数。使用它时,唯一要注意的是你必须使用 renderTableNew() 而不是 renderTable