alex_stephenson
alex_stephenson

Reputation: 99

Inputting variable data in shiny

I'm looking to make a shiny app where users upload a text file and can input the terms they want filter (so sentences that have two particular words or phrases). then they can download the results. My script so far looks like:

ui <- fluidPage(
  titlePanel("Download data"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose .txt file",
                multiple = F,
                accept = c(".txt")),
      textInput('energy_co', 'Name of energy company'),
      textInput('asset', 'name of Asset Manager'),
      downloadButton("downloadData", "Download")
    ),
    
    mainPanel(
      tableOutput("table")
    )
    
  )
)




server <- function(input, output, session) {
  
  options(shiny.maxRequestSize=30*1024^2)

  
  output$table <- renderTable({  
  req(input$file1)
  
    data <- read_lines(input$file1$datapath)
    text_df <- as_data_frame(data)
    
    company_data <- text_df %>% 
      filter(str_detect(terms, input$asset)) %>%   
      filter(str_detect(terms, input$energy_co)) %>% 
      distinct(.)
    
    company_data
    
    })
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(company_data, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(company_data, file1, row.names = FALSE)
    }
  )
  
}


shinyApp(ui, server)

I can upload the dataset (a .txt file) but nothing happens either when I try and render the table or when I try and download the results as a csv. I think the server script might need to be reactive? any help appreciated

Upvotes: 0

Views: 94

Answers (1)

YBS
YBS

Reputation: 21287

Try this

ui <- fluidPage(
  titlePanel("Download data"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose .txt file",
                multiple = F,
                accept = c(".txt")),
      textInput('energy_co', 'Name of energy company'),
      textInput('asset', 'name of Asset Manager'),
      downloadButton("downloadData", "Download")
    ),
    
    mainPanel(
      tableOutput("table")
    )
    
  )
)


options(shiny.maxRequestSize=30*1024^2)

server <- function(input, output, session) {
  
  company_data <- reactive({
    req(input$file1,input$asset,input$energy_co)
    
    data <- read_lines(input$file1$datapath)
    text_df <- as_data_frame(data)
    
    company_data <- text_df %>% 
      filter(str_detect(terms, input$asset)) %>%   
      filter(str_detect(terms, input$energy_co)) %>% 
      distinct(.)
    company_data
  })
  
  
  output$table <- renderTable({  
    
    company_data()
    
  })
  
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(company_data, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(company_data(), file1, row.names = FALSE)
    }
  )
  
}


shinyApp(ui, server)

Upvotes: 2

Related Questions