Как записать данные из блестящего приложения в файл Excel / CSV? Именно я хочу записать значения цены акций в файл excel / csv - PullRequest
1 голос
/ 29 апреля 2020

Я хочу записать стоимость акций в файл excel / csv, но не могу этого сделать. Отображается следующий код ошибки: 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.) Где, когда я использую реактивные данные (dataInput), сообщение об ошибке читается как «невозможно привести класс» c («реактивныйExpr», «реактивный») »к data.frame

Код прилагается:

Загрузка пакетов ----

library(shiny)
library(quantmod)
#edited the code.this can be run directly

# User interface ----
ui <- fluidPage(
  titlePanel("stockVis"),

  sidebarLayout(
    sidebarPanel(
      helpText("Select a stock to examine.

        Information will be collected from Yahoo finance."),
      textInput("symb", "Symbol", "SPY"),

      dateRangeInput("dates",
                     "Date range",
                     start = "2013-01-01",
                     end = as.character(Sys.Date())),

      br(),
      br(),

      checkboxInput("log", "Plot y axis on log scale",
                    value = FALSE)

      #checkboxInput("adjust",
      #"Adjust prices for inflation", value = FALSE)
    ),

    mainPanel(plotOutput("plot"), tableOutput("view")))



)


# Server logic
server <- function(input, output) {

  dataInput <- reactive({
    getSymbols(input$symb, src = "yahoo",
               from = input$dates[1],
               to = input$dates[2],
               auto.assign = FALSE)


  }) Blockquote
  output$plot <- renderPlot({

    chartSeries(dataInput(), theme = chartTheme("white"),
                type = "line", log.scale = input$log, TA = NULL)
  })

  output$view <- renderTable({(dataInput() )
  }, include.rownames = TRUE)
  #trying to export the data
  write.csv(dataInput(),row.names = TRUE)

}`enter code here`

# Run the app
shinyApp(ui, server)

1 Ответ

0 голосов
/ 29 апреля 2020

В реактивном контексте он пытается выполнить код сразу после запуска приложения Shiny и , как только начинает меняться символ акции. Чтобы разрешить запись файла только тогда, когда пользователь готов, измените «реактивный» на «наблюдать событие». Кнопка «Выполнить» была добавлена, чтобы заставить его работать. Скопируйте и вставьте приведенный ниже код.

Кстати, поскольку в файле write.csv отсутствует команда file =, которая прокручивает файл csv в консоль.

Это хорошая утилита, которая позволяет легко загружать цены на акции в CSV-файл.

library(shiny)
library(quantmod)
#edited the code.this can be run directly

# User interface ----
ui <- fluidPage(
  titlePanel("stockVis"),

  sidebarLayout(
    sidebarPanel(
      helpText("Select a stock to examine.

        Information will be collected from Yahoo finance."),
      textInput("symb", "Symbol", "SPY"),

      dateRangeInput("dates",
                     "Date range",
                     start = "2013-01-01",
                     end = as.character(Sys.Date())),

      br(),
      br(),

      checkboxInput("log", "Plot y axis on log scale",
                    value = FALSE),

      #checkboxInput("adjust",
      #"Adjust prices for inflation", value = FALSE),
      actionButton(inputId = "run",label="Run"),
    ),

    mainPanel(plotOutput("plot"), tableOutput("view")))

)

# Server logic
server <- function(input, output) {

  dataInput <- function() {
    getSymbols(input$symb, src = "yahoo",
               from = input$dates[1],
               to = input$dates[2],
               auto.assign = FALSE)
  }

  observeEvent (input$run, {

   output$plot <- renderPlot({

    chartSeries(dataInput(), theme = chartTheme("white"),
                type = "line", log.scale = input$log, TA = NULL)
    })

    output$view <- renderTable({(dataInput() )
    }, include.rownames = TRUE)
    #trying to export the data
    write.csv(dataInput(),row.names = TRUE)

  })
}
# Run the app

shinyApp(ui, server)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...