DT 和 Shiny:使用过滤器格式化数据表中的数字

emp*_*i75 5 r shiny dt

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

  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)
Run Code Online (Sandbox Code Playgroud)

Shr*_*ree 5

看来您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)
Run Code Online (Sandbox Code Playgroud)