Nick Riches
Nick Riches

Reputation: 411

Using scan in reactive statement

I'm trying to write a simple program in R using Shiny. The program reads a text files selected by the user, and then displays this as an .html object. I'm using the 'scan' function to read the text file (NB currently only trying to output the first line). The program runs, but the output is not updated. Why isn't the output being updated? Thanks.

library(shiny)

shinyApp(

  ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          fileInput("text_file", "Choose text file",
                    multiple = FALSE,
                    accept = c(".txt")
          )
        ),
        mainPanel(htmlOutput("example"))
      )
    ), 

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

    text <- reactive({
            req(input$text_file)
            x <- scan(input$text_file, what = "string", sep = "\n")[1]
            })
    # text output
    output$example <- reactive({
        renderUI({
          HTML(x)
          })
    })
  }
)

shinyApp(ui, server)

Upvotes: 0

Views: 123

Answers (1)

Vishesh Shrivastav
Vishesh Shrivastav

Reputation: 2139

There are some changes you need to make:

  1. File reading a file, you have to ask the file to be read from input$inputId$datapath and not input$inputId.
  2. Your renderUI() should return text() and not x, as text() is your reactive object being rendered.
  3. You do not need to add reactive() to any render functions in shiny as they are already reactive.

Change your server to the following:

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

  text <- reactive({
    req(input$text_file)
    x <- scan(input$text_file$datapath, what = "string", sep = "\n")[1]
  })

  # text output
  output$example <- renderUI({
      HTML(text())
    })
}

Upvotes: 2

Related Questions