首页 > 解决方案 > 在 Shiny 中下载过滤后的 tableOutput

问题描述

我有以下数据:

> data
        products         id
1             P1     280386
2             P1     285184
3             P2     293154
4             P1     294245

我已经构建了一个简单的闪亮代码。我首先过滤表,然后我想下载过滤后的表。我写以下

library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)

data <- read.csv("Desktop/data.csv")
products <- unique(data$products)


ui <- fluidPage(
  fluidRow(
    column(4, 
           selectInput("product", "Product", products,
                       multiple = TRUE), 
           downloadButton("download", "Download")),
    column(8, 
           tableOutput("errorTable")
    )
  )
)

server <- function(input, output, session) {
  
  output$errorTable <- renderTable({
    subset(data, products == input$product) 
  }
  )
  
  
  output$download <- downloadHandler(
    filename = function() {
      paste("data-",Sys.Date(), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(data, file)
    }
  )
  
}

shinyApp(ui, server)

但是,此代码仅下载完整表,而不是过滤后的表。我搜索了一些问题,但没有一个具体解释这个案例。提前致谢

标签: rshiny

解决方案


尝试这个

library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)

data <- read.csv("Desktop/data.csv")
products <- unique(data$products)


ui <- fluidPage(
  fluidRow(
    column(4, 
           selectInput("product", "Product", products,
                       multiple = TRUE), 
           downloadButton("download", "Download")),
    column(8, 
           tableOutput("errorTable")
    )
  )
)

server <- function(input, output, session) {
  
  
  #you need to create a reactive object with a NULL starting value
  listofitems <- reactiveValues(data = NULL )
  
  #observe the changes in input$product and update the reactive object 
  observeEvent( input$product, {
    print("Hello: observeEvent for input$product is triggered")
    #debug using browser()
    listofitems$data <-  subset(data, products == input$product) 

    showNotification("Products updated",
                     type =  "message",
                     duration = 4,
                     closeButton = TRUE)
  }, ignoreInit = T,ignoreNULL = TRUE)
  

    
    output$errorTable <- renderTable({
      listofitems$data
    }
    )
  
  
  output$download <- downloadHandler(
    filename = function() {
      paste("data-",Sys.Date(), ".csv", sep = "")
    },
    content = function(file) {
      write.csv(listofitems$data, file)
    }
  )
  
}

shinyApp(ui, server)

推荐阅读