2017-06-17 64 views
0

我花了很長時間試圖弄清楚如何啓用只下載到我已經過濾的行的下載。我已經獲得rows_selected來按預期工作,但rows_all返回選定的行數,但不是正確的行,即不是「G」的行,而是下載返回'A'&'B'的行。R Shiny rows_all返回已過濾的行而不返回預期的結果

我創建了一個簡單的應用程序,在將其應用到我的應用程序之前找出此功能。以下是代碼。

任何和所有的幫助,非常感謝!我已經在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) 

回答

2

問題的產生是因爲在下載的時候,你是不是你的引用過濾表,但原始表,並應用在原表中的濾波的行號。下載時,需要引用已過濾的表格,如果將其存儲在反應值中並在構建數據表格和下載時使用該反應表,則可能會出現這種情況:

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

    # store the currently filtered DS in a reactive 
    filteredDS <- reactive({ 
    if (!"ALL" %in% input$product){ 
     return(DS[DS$PRODUCT %in% input$product,]) 
    }else{ 
     return(DS) 
    } 
    }) 

    # display the currently filtered DS 
    output$ds <- DT::renderDataTable({ 
    filteredDS() 
    }, 
    rownames = T, 
    server = F) 

    # download filtered rows 
    output$downloadFiltered <- downloadHandler(
    filename = "filteredData.csv", 
    content = function(file){ 
     s = input$ds_rows_all 
     write.csv(filteredDS()[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(filteredDS()[s, , drop = F], file, row.names = T) 
    } 
) 
} 
+0

謝謝!我在reddit上得到了類似的回覆,當我剛剛看到您的評論時,我只是來這裏更新答案。我非常感謝你的幫助,這正是解決方案! – user2299914