通过按钮/单击过滤数据表(R Flexdashboard)

Filtering a DataTable by button / one click (R Flexdashboard)

我在 Flexdashboard 中使用 DT::datatable 为大约 100 个不同的国家/地区提供一些月度 KPI。仪表板的一些用户对其中五个特别感兴趣,因此我正在寻找一种解决方案来轻松筛选这些国家/地区。

我的想法是在“导出按钮”旁边生成一个按钮,该按钮将仅过滤那五行的数据。再次单击它会最完美地再次显示原始 table。 我发现可以指定 custom buttons 但我仍然不知道如何解决我的问题。

这是我目前得到的 table 的一个小例子:

# Random Data Frame
df <- data.frame(Country = paste("Country", 1:100, sep = "_"), 
                 Revenue = rnorm(n = 100, mean = 5000, sd = 2000))

# Data Table used in Dashboard
datatable(df, class = "hover", rownames = FALSE , extensions = 'Buttons', options = list(
  pageLength = 5,
  responsive = TRUE,
  dom = 'Bftip',
  buttons = c('copy', 'csv'),
  columnDefs = list(list(className = 'dt-center', targets = "_all"))
)) %>% formatCurrency(columns = "Revenue")

感谢您的帮助!

下面是一个可在 Shiny 中重现的示例,因为我认为您尝试做的事情在静态文档中是不可行的。我假设你已经设置了 runtime: shiny.

library(DT)
library(shiny)

countries <- data.frame(
  cns = LETTERS,
  value = runif(26, 1, 4)
)

TOP5 <- c("A", "B", "X", "Y", "Z")

ui <- fluidPage(
  actionButton("filter", "Filter countries of interest"),
  DTOutput("table")
)

server <- function(input, output, session) {

  output$table <- renderDT({

    sel <- if(input$filter %% 2 == 0) countries$cns else TOP5

    countries %>% 
      filter(cns %in% sel) %>% 
      datatable()
  })

}

shinyApp(ui, server)

我会使用嵌入在您的 flexdashboard 文件中的 shinyApp

注意在 YAML(前面的内容)中你需要设置:runtime: shiny

你的关键代码是:

UI

中的下拉选择代码

Choices 您可以指定您的团队感兴趣的五个国家/地区。

  # Input: Choose dataset ----
  selectInput("dataset", "Choose a Country",
              choices = as.character(unique(df$Country)))

下载按钮

在服务器端,逻辑仅适用于下载过滤后的数据。

  # Button
  downloadButton("downloadData", "Download")

Reactive Component This is important as it allows for the data to be dynamically filtered based on the input selection of the user.

  # Reactive value for selected dataset ----
  datasetInput <- reactive({
      df %>% filter(Country ==input$dataset)
  })

最后,这允许您下载过滤后的数据

  # Downloadable csv of selected dataset ----
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(as.character(input$dataset), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(datasetInput(), file, row.names = FALSE)
    }

Useful Links

Shiny App Example

Using Shiny in Flex Dashboards

FULL *.Rmd 代码如下

---
title: "Filter Data"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r global, include=FALSE}
# load data in 'global' chunk so it can be shared by all users of the dashboard
library(shiny)
library(dplyr)
# Random Data Frame
df <- data.frame(Country = paste("Country", 1:100, sep = "_"), 
                 Revenue = rnorm(n = 100, mean = 5000, sd = 2000))
```

To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).

## Inputs and Outputs

You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change.  This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot.

```{r eruptions, echo=FALSE}
ui <- fluidPage(
  
  # App title ----
  titlePanel("Downloading Data"),
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      # Input: Choose dataset ----
      selectInput("dataset", "Choose a Country",
                  choices = as.character(unique(df$Country))),
      
      # Button
      downloadButton("downloadData", "Download")
      
    ),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      tableOutput("table")
      
    )
    
  )
)

# Define server logic to display and download selected file ----
server <- function(input, output) {
  
  # Reactive value for selected dataset ----
  datasetInput <- reactive({
      df %>% filter(Country ==input$dataset)
  })
  
  # Table of selected dataset ----
  output$table <- renderTable({
    datasetInput()
  })
  
  # Downloadable csv of selected dataset ----
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(as.character(input$dataset), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(datasetInput(), file, row.names = FALSE)
    }
  )
  
}
# Create Shiny app ----
shinyApp(ui, server)
```