R 中的反应性问题 - 你试图做一些只能从反应性消费者内部完成的事情

Issues with reactivity in R - You tried to do something that can only be done from inside a reactive consumer

我试图将此代码放入具有动态日期和股票代码选择的 Shiny 中,但我收到以下错误 如果没有活动的反应上下文,则不允许操作。 您试图做一些只能从反应性消费者内部完成的事情。

library(quantmod)
library(PerformanceAnalytics)

dt <- "2017-2-1"

aapl <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)
aaplClose <- getSymbols.yahoo("AAPL", from=dt, auto.assign = F)[,6]

aaplRets <- na.omit(dailyReturn(aaplClose, type="log"))

这是我的闪亮实现

library(shiny)
library(quantmod)
library(PerformanceAnalytics)
#dt <- "2017-2-1"

ui <- fluidPage(
  dateInput("dt", "Select a date:"),
  textInput("tkr", "Enter a ticker symbol"),
  plotOutput("myplot")
)

server <- function(input, output, session) {
  aapl <- reactive ({
    getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)
    })
  aaplClose <- reactive ({
    getSymbols.yahoo(input$tkr, from=input$dt, auto.assign = F)[,6]
  })
  aaplRets <- na.omit(dailyReturn(aaplClose(), type="log"))
  
  output$myplot <- renderPlot(
    { chartSeries(aapl())}
  ) 
}

shinyApp(ui, server)

既然你有一个文本输入到 select 代码,数据不应该被称为苹果,因为它可以是一切。将所有内容保持在反应性上下文中:

library(shiny)
library(quantmod)
library(PerformanceAnalytics)


ui <- fluidPage(
  dateInput("dt", "Select a date:", value = "2017-2-1"),
  textInput("tkr", "Enter a ticker symbol", value = "AAPL"),
  plotOutput("myplot")
)

server <- function(input, output, session) {
  data <- reactive({
    getSymbols.yahoo(input$tkr, from = input$dt, auto.assign = F)
  })

  output$myplot <- renderPlot({
    chartSeries(data())
  })
}

shinyApp(ui, server)

或使用字母表: