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 story short, please just look at the following code. I was trying to fetch data from Google Finance and calculated the smoothed variance.
stock2 <-
reactive(
getSymbols(
toupper(input$ticker2),
from = as.Date(input$date2[1]) - 150,
to = input$date2[2],
src = "google",
auto.assign = F
)
)
stock3 <- reactive(as.data.table(stock2()))
stock <- reactive(as.data.frame(stock3()))
stock.return <- reactive(diff(log(stock()[, 5])))
stock.mu <- reactive(mean(stock.return()))
stock.var <- reactive((stock.return() - stock.mu()) ^ 2)
stock.var.smoothed <- reactive(rep(0, length(stock.return())))
Code above works totally fine and I have tested that.
So the problem is the following code, I want to assign a vector based on some calculation but I don't know the proper way to do it.
stock.var.smoothed <- reactive({
for (i in 2:length(stock.var())) {
stock.var.smoothed[1] <<- stock.var()[1]
stock.var.smoothed[i] <<-
(1 - input$alpha) * stock.var.smoothed()[i - 1] + input$alpha * stock.var()[i]
}
})
The for loop doesn't work at all.
The error code is
Error: object of type 'closure' is not subsettable
But I already used () for the variables inside the function. So I have no idea how to fix that.
BTW, I also tried the following code
for (i in 2:length(stock.return())) {
stock.momentum.smoothed[1] <- reactive(stock.momentum()[1])
stock.momentum.smoothed[i] <-
reactive((1 - input$beta) * stock.momentum.smoothed()[i - 1] + input$beta * stock.return()[i])
}
The error code is
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
I appreciate anyone that could give any help. Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…