簡體   English   中英

使用閃亮的應用程序創建反應式數據框

[英]Creating a reactive dataframe with shiny apps

我試圖讓這種反應性返回一個我可以用劇情操縱的數據框。

avghour <- reactive({
    result <- data.frame()
    start_date <- as.numeric(unlist(input$i6[1]))
    end_date <- as.numeric(unlist(input$i6[2]))
    mkw <- maxkwpeakdates[(maxkwpeakdates >= start_date & maxkwpeakdates <= 
                             end_date) & !is.na(maxkwpeakdates), ]
    mkw <- na.omit(mkw)
    mopkw <- maxonpeakkwdates[(maxonpeakkwdates >= x & 
                                 maxonpeakkwdates <= y) & !is.na(maxonpeakkwdates), 
                              ]
    mopkw <- na.omit(mopkw)
    mkwhour <- data.frame(as.data.frame(apply(mkw, 2, hour)))
    mopkwhour <- as.data.frame(apply(mopkw, 2, hour))
    mkwhour <- as.data.frame(sapply(mkwhour, tabulate, 24))
    mopkwhour <- as.data.frame(sapply(mopkwhour, tabulate, 24))
    mkwhour <- as.data.frame(apply(mkwhour, 1, mean))
    mopkwhour <- as.data.frame(apply(mopkwhour, 1, mean))
    result <- data.frame(mkwhour, mopkwhour)
    colnames(result) <- c("1", "2")
    return(result)
  })

我希望能夠繪制結果數據框。 當我調試我的應用程序時,結果發現avghour被保存為一個函數而不是數據框。 無功要求的值是強制反應正常更新但我不能將結果保存為數據幀。 我是否正確使用反應? 我需要以另一種方式做這件事嗎?

UPDATE

I have changed my server code to be like this:

server <- function(input, output) {

  averages <- reactiveValues(hourly = avghour(input$'i6'[1], input$'i6'[2]))

  observeEvent(input$submit,{
    averages$hourly <- avghour(input$'i6'[1], input$'i6'[2])
  })

  output$"1" <- renderPlotly({
    plot_ly() %>%  
      add_trace(type = 'bar',
                data=averages$hourly,
                x=~'1',
                y=~'2')
  })

}

getHourlyAverage與我之前的功能相同。 現在我收到error: operation not allowed without an active reactive context. 如何在用戶輸入中使用observeEvent和reactiveValues?

我建議將數據幀存儲在所謂的reactiveValues列表中。 然后它們具有與使用reactive函數計算的事物相同的反應特性(因為當原始物質改變時,將觸發依賴於它們的其他反應物),但是您可以使用它們的所有元素來操縱它們。

一般來說,建議只使用反應函數可以逃脫的簡單程序應該這樣做,但我發現當事情變得更復雜時,經常會導致死胡同,因為沒有邏輯位置來存儲和更新數據。

請注意, reactiveValues是一個列表,您可以在其中存儲多個內容,從而將相關內容保持在一起。 該名單的所有成員都將被動反應。

這是一個使用plotly的一個非常簡單的例子:

library(plotly)
library(shiny)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  actionButton("regen","Generate New Points")
))

server <- shinyServer(function(input, output) {

  n <- 100  
  rv <- reactiveValues(m=data.frame(x=rnorm(n),y=rnorm(n)))

  observeEvent(input$regen,{
    rv$m <- data.frame(x=rnorm(n),y=rnorm(n))
  })

  output$myPlot <- renderPlotly({
     plot_ly() %>%  add_markers(data=rv$m,x=~x,y=~y  )
  })
})
shinyApp(ui, server)

這是一個幫助可視化它的屏幕截圖:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM