R Shiny rows_all返回未返回预期结果的过滤行

时间:2017-06-17 06:45:37

标签: r shiny

我花了很长时间试图弄清楚如何只下载我过滤到的行。我已经使rows_selected按预期工作,但rows_all返回所选择的行数,但不是正确的行,即代替“G”和“行”的行。 'H'下载返回'A'& 'B'。

我创建了一个简单的应用来确定此功能,然后再将其应用到我的应用中。以下是代码。

非常感谢任何和所有帮助!我已经在reddit.com/r/rlanguage上发布了这个帖子,但由于观众人数众多,我在这里发帖。

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

DS <- data.frame(PRODUCT = c("A","B","C","D","E","F","G","H","I","J"),
             UNITS = runif(n = 10, min = 0, max = 100),
             REVENUE = runif(n = 10, min = 1000, max = 100000))

DS <- DS %>% mutate(PRICE = REVENUE / UNITS)

# Define UI for application
ui <- fluidPage(
 titlePanel("Download Selected Data Example"),
  br(),
  fluidRow(
    column(4,
           selectInput("product",
                       "Select one of the following products:",
                       c("ALL",
                         unique(as.character(DS$PRODUCT))),
                       multiple = T))),
  br(),
  fluidRow(
  DT::dataTableOutput("ds"),
  downloadButton("downloadFiltered", "Download Filtered Rows"),
  downloadButton("downloadSelected", "Download Selected Rows")))

# Define server logic
server <- function(input, output) {
 output$ds <- DT::renderDataTable({

data <- DS

if (input$product != "ALL"){
  data <- data[data$PRODUCT %in% input$product,]
}

data

},
rownames = T,
server = F)

# download filtered rows
output$downloadFiltered <- downloadHandler(
 filename = "filteredData.csv",
 content = function(file){
   s = input$ds_rows_all
   write.csv(DS[s, , drop = F], file, row.names = T)
 })

# download selected rows
output$downloadSelected <- downloadHandler(
   filename = "selectedData.csv",
   content = function(file){
     s = input$ds_rows_selected
     write.csv(DS[s, , drop = F], file, row.names = T)
   }
  )
}

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

1 个答案:

答案 0 :(得分:2)

出现问题是因为在下载时,您没有引用过滤后的表,而是引用原始表,并在原始表上应用过滤后的行号。下载时,您需要引用过滤后的表格,如果您将其存储在无效值中,并在构建数据表和下载时使用该被动表格,则可以参考:

const matchMaker = () => {
    let memo = [‘a’, ‘b’];
    return (c, i, d) => {
        memo.unshift(c);
        return memo[1] + memo[2] + c === 'itt';
    }
};

data.filter(matchMaker());