代码之家  ›  专栏  ›  技术社区  ›  JJJ abhijeet104

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

  •  0
  • JJJ abhijeet104  · 技术社区  · 7 年前

    当制作一个有很多表包含一些NA值的闪亮应用程序时,可以全局定义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)
    

    enter image description here

    ourTable2 ,也就是说,没有 NA 在输出中打印,而不必为我添加的每个表显式指定。

    0 回复  |  直到 7 年前
        1
  •  1
  •   Soren    7 年前

    如果愿意,可以在全局.R文件(或在server.R)文件中定义以下内容。它将在您的表上工作,如果整个表为NA,则返回“”。如果传递复杂的对象,如嵌入的列表列表,则需要更复杂一些。但是,印刷数据帧就像在手术室工作一样。

    在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)
    }
    

     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      
    
        2
  •  0
  •   JJJ abhijeet104    7 年前

    佩里卡多的 comment under my question

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

    显然,这个“技巧”可以用来定义 renderTable() 可以用不同的参数创建多个这样的函数。当使用这个时,唯一需要注意的是你必须使用 renderTableNew() 而不是 renderTable .

    推荐文章