I'm trying to download the source data (mpg) I used to generate the selected rows in a DT table. The table shows aggregated results based on an input grouper from the source data.
I tried to: first get the row number using the _rows_selected function, then accumulate a list of the value in the grouper column, then identify the row indices of these value in the source data, then write the exported the csv based on these row indices and the source data.
But it didn't seem to work and I couldn't figure out why.
library(datasets)
library(shiny)
library(dplyr)
library(plotly)
library(ggplot2)
library(DT)
library(crosstalk)
data("mpg")
mpg = data.frame(mpg)
#convert all column input from character to factor (or assure they are all factor)
for(i in 1:dim(mpg)[2]){
mpg[,i] = type.convert(mpg[,i])
i = i+1
}
#mpg$manufacturer = type.convert(mpg$manufacturer)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Analyze MPG table"),
# Sidebar with a dropdown menu selection input for key meausre component
sidebarLayout(
sidebarPanel(
selectInput("yInput", "Measuring element: ",
colnames(mpg), selected = colnames(mpg)[9]),
selectInput('xInput', 'Grouper: ',
colnames(mpg), selected = colnames(mpg)[1]),
selectInput('xInput2', 'Filter Column: ',
colnames(mpg), selected = colnames(mpg)[2]),
p(downloadButton('x0', 'Download Source Data of Selected Rows',
class = 'text-center'))
),
# Show a plot of the generated distribution
mainPanel(
uiOutput('filter'),
plotlyOutput("barPlot"),
DTOutput('table1')
)
)
)
server <- function(input, output) {
output$filter = renderUI({
selectInput('inputF2', 'Filter Item: ',
c('No Filter', unique(mpg %>% select(input$xInput2))))
})
mpg_sub <- reactive({
if (req(input$inputF2) != 'No Filter') {
mpg_sub <- mpg %>% filter_at(vars(input$xInput2), any_vars(. == input$inputF2))
} else{
mpg_sub <- mpg
}
return(mpg_sub)
})
by_xInput <- reactive({
mpg_sub() %>%
group_by_at(input$xInput) %>%
# n() can replace the length
# convert string to symbol and evaluate (!!)
summarize(n = n(), mean_y = mean(!! rlang::sym(input$yInput)))
})
output$table1 = renderDT(
datatable(by_xInput(),
extensions = 'Buttons',
options = list(dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print'))
)
)
#####here is where I have the issue...
output$x0 = downloadHandler(
'Source Data_selected.csv',
content = function(file){
s0 = input$table1_rows_selected
grouper = by_xInput()[s0, 1]
big = mpg_sub()[, match(as.character(input$xInput), colnames(mpg_sub()))]
position = which(!is.na(match(big, grouper)))
write.csv(mpg_sub()[position, , drop = F], file)
}
)
}
shinyApp(ui = ui, server = server)