For loop inside reactive function in Shiny

前端 未结 1 435
醉梦人生
醉梦人生 2020-12-12 03:03

I met a problem with for loop in Shiny server and no one can find out how to fix it till now. I have been working on this for days but still didn\'t get any progress. Long s

相关标签:
1条回答
  • 2020-12-12 03:40

    Your subset assignment to the reactive (stock.var.smoothed[1] <<-) simply doesn’t make sense: this operation wouldn’t be what you want, even without the subsetting (it would replace your reactive object with a non-reactive value; i.e. it would stop being reactive).

    You can create and assign to variables inside your reactive expression. But don’t assign to the global environment (i.e. don’t use <<-), and don’t try to reassign the reactive object itself. Instead, create a local temporary variable:

    stock.var.smoothed <- reactive({
      value <- numeric(length(stock.var()))
      value[1] <- stock.var()[1]
    
      for (i in 2 : length(stock.var())) {
        value[i] <- (1 - input$alpha) * value[i - 1] + input$alpha * stock.var()[i]
      }
    
      value
    })
    

    Here, value could be any name (including stock.var.smoothed — but this would be a different variable than your reactive, because it’s in a different scope).

    Furthermore, I’m pretty sure that this code be written without a loop and temporary variable (but it’s not immediately obvious how it would look like to me).

    Finally, a note on code style: don’t use . inside variable names. This is confusing, since it’s also used for S3 dispatch to separate the method’s generic name and class name. A common convention in R is to use underscores instead (stock_var_smoothed).

    0 讨论(0)
提交回复
热议问题