【问题标题】:DT and Shiny: Formatting numbers in a datatable with filtersDT 和 Shiny:使用过滤器格式化数据表中的数字
【发布时间】:2019-04-21 01:34:40
【问题描述】:

我有一个带有数据表的闪亮应用,我想完成两件事:

  1. 我想在 DTOutput 顶部添加过滤器
  2. 我想将表格中的数字设置为百分比格式。

我只能做到其中之一。因此,如果我只使用过滤器(参见代码中的尝试#3),它可以工作,但我无法将数字格式化为百分比。如果我尝试格式化数字(请参阅代码中的 attpemts #1 和 #2),则过滤器会消失,但数字的格式正确。我还在控制台中收到警告消息:

"当 expr 生成数据表时,renderDataTable 会忽略 ... 参数 对象”

这对我没有多大帮助,因为我对 Shiny 和 R 很陌生。

我找到了有关格式化数字或过滤表的教程并回答了问题,但我显然遗漏了一些东西...如果您能指导我找到答案或在下面的代码中发现错误,我将不胜感激。

可在此处重现 app.R

library(shiny)
library(dplyr)
library(DT)

# Define UI 
ui <- fluidPage(
  actionButton("start", "Click to Start") 
  DTOutput('tbl1'),
  DTOutput('tbl2'),
  DTOutput('tbl3')
)

# Define Server
server = function(input, output) {

  #Attempt #1: gives me the formatted numbers but no filter.
  x <- eventReactive(input$start, iris %>% dplyr::filter(Species == "setosa") %>% datatable %>% formatPercentage(2:3, digits=2))
  output$tbl1<-  DT::renderDT(x(), filter="top")


  #Attempt #2: gives me the formatted numbers but no filter.
  y <- eventReactive(input$start, iris %>% dplyr::filter(Species == "setosa"))
  output$tbl2 <-  DT::renderDT(y() %>% datatable %>% formatPercentage(2:3, digits=2), filter="top")


  #Attempt #3: I get the filter, if I don't try to format the numbers
  z <- eventReactive(input$start, iris %>% dplyr::filter(Species == "setosa"))
  output$tbl3 <-  DT::renderDT(z(), filter="top")


}

# Run the application 
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny dt


    【解决方案1】:

    似乎您在第三次尝试中忘记使用datatable() 函数。这就是你需要的 -

    library(shiny)
    library(dplyr)
    library(DT)
    
    # Define UI 
    ui <- fluidPage(
      actionButton("start", "Click to Start"),
      DTOutput('tbl3')
    )
    
    # Define Server
    server = function(input, output) {
    
      z <- eventReactive(input$start, {
        iris %>% dplyr::filter(Species == "setosa")
      })
    
      output$tbl3 <-  DT::renderDT({
        datatable(z(), filter="top") %>% 
          formatPercentage(2:3, digits=2)
      })     
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 2016-11-15
      • 2022-01-22
      • 2021-11-20
      • 2016-04-24
      • 2016-01-15
      • 2013-07-01
      • 2021-12-13
      • 2020-03-02
      相关资源
      最近更新 更多