【问题标题】:Using scan in reactive statement在响应式语句中使用扫描
【发布时间】:2018-11-04 16:23:46
【问题描述】:

我正在尝试使用 Shiny 在 R 中编写一个简单的程序。程序读取用户选择的文本文件,然后将其显示为 .html 对象。我正在使用“扫描”功能来读取文本文件(NB 目前只尝试输出第一行)。程序运行,但输出未更新。为什么没有更新输出?谢谢。

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)

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    您需要进行一些更改:

    1. 文件读取文件,你必须要求从input$inputId$datapath而不是input$inputId读取文件。
    2. 您的renderUI() 应该返回text() 而不是x,因为text() 是您正在呈现的反应对象。
    3. 您无需将reactive() 添加到任何闪亮的render 函数中,因为它们已经是响应式的。

    将您的服务器更改为以下内容:

    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())
        })
    }
    

    【讨论】:

    • 谢谢。完美运行。感谢您对关键概念的解释。
    猜你喜欢
    • 2014-08-07
    • 2015-02-24
    • 1970-01-01
    • 2018-08-11
    • 2013-02-10
    • 1970-01-01
    • 2013-10-17
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多