1

我了解反应值会根据此处的描述通知依赖于该值的任何反应函数

基于此,我想利用这个属性并创建一个 for 循环,为我的反应值对象分配不同的值,反过来我期望另一个反应函数重新执行自身,因为反应值在 for 循环内发生变化. 下面是我正在尝试做的一个简化示例:

这是ui.R

library(shiny)

# Define UI 
shinyUI(pageWithSidebar(
  titlePanel("" ,"For loop with reactive values"),
  # Application title
  headerPanel(h5(textOutput("Dummy Example"))),

  sidebarLayout(
  #Sidebar
    sidebarPanel(
      textInput("URLtext", "Enter csv of urls", value = "", width = NULL, placeholder = "Input csv here"),
      br()

    ),

    # Main Panel
    mainPanel(

      h3(textOutput("caption")) 


    )
  )
))   

这是服务器文件:

library(shiny)

shinyServer(function(input, output) {

  values = reactiveValues(a = character())
  reactive({
    url_df = read.table(input$URLtext)
    for (i in 1:5){
      values$a = as.character(url_df[i,1])
      Sys.sleep(1)
    }
  })
  output$caption <- renderText(values$a) 
})

这没有给出预期的结果。实际上,当我检查它的内容时,values$a 它是空的。请帮忙!

4

1 回答 1

0

与其使用循环,不如for尝试使用invalidateLater()计步器。这是一个为我运行的工作示例,其中包含通过快速谷歌搜索找到的示例 csv (第一列是行索引 1-100)。

library(shiny)

# OP's ui code
ui <- pageWithSidebar(
  titlePanel("" ,"For loop with reactive values"),
  headerPanel(h5(textOutput("Dummy Example"))),
  sidebarLayout(
    sidebarPanel(
      textInput("URLtext", "Enter csv of urls", value = "", width = NULL, placeholder = "Input csv here"),
      br()
    ),
    mainPanel(
      h3(textOutput("caption")) 
    )
  )
)

server <- function(input, output, session) {
  # Index to count to count through rows 
  values = reactiveValues(idx = 0)

  # Create a reactive data_frame to read in data from URL
  url_df <- reactive({
    url_df <- read.csv(input$URLtext)
  })

  # Reset counter (and url_df above) if the URL changes
  observeEvent(input$URLtext, {values$idx = 0})

  # Render output
  output$caption <- renderText({
    # If we have an input$URLtext
    if (nchar(req(input$URLtext)) > 5) {
      # Issue invalidation command and step values$idx
      if (isolate(values$idx < nrow(url_df()))) {
        invalidateLater(0, session)
        isolate(values$idx <- values$idx + 1)
      }
    }
    # Sleep 0.5-s, so OP can see what this is doing
    Sys.sleep(0.5)
    # Return row values$idx of column 1 of url_df
    as.character(url_df()[values$idx, 1])
  })
}

shinyApp(ui = ui, server = server)
于 2016-12-03T19:42:49.720 回答