闪亮光栅的反应式表达

reactive expression for raster in shiny

我正在开发一个简单闪亮的应用程序。 这是我的数据。

  library(data.table)
  library(ggthemes)
  library(ggplot2)
  library(shiny)

  tempList <- list()

  for(i in 1989:1991){

      temp <- as.data.frame(cbind(runif(10,-10.85, 20.02),runif(10, 49.82,59.47)))
      temp$value <- rnorm(10)
      temp$Year <-i
      tempList[[i]] <- temp
  }

  my.df <- rbindlist(tempList)
  names(my.df)[1:2] <- c('lon', 'lat')

我想制作一个闪亮的应用程序,根据用户的年份显示每年的栅格 select

  ui <- fluidPage(

          titlePanel('My dat'),
          sliderInput('yearRef','Select Year',min=1989,max=1991,value=1),

          plotOutput(outputId = 'test')
        )


  server <- function(input, output) {

    tempI <- reactive({my.df %>% dplyr::filter(Year == input$yearRef)})

    output$test <- renderPlot({
    ggplot() + geom_raster(data = tempI, aes(x = lon, y = lat, fill = value)) +
    theme_map() + coord_equal() + scale_fill_viridis_c(option = 'C') 
    })
  }

  shinyApp(ui, server)

它给了我一个错误,tempI 不是数据帧,据我所知这是因为 tempI 是 class reactiveExpr。我该如何更正它?

shiny 中使用反应式表达式时,您必须使用括号。 你的情况:

renderPlot({
    ggplot() + geom_raster(data = tempI(), aes(x = lon, y = lat, fill = value)) +
    theme_map() + coord_equal() + scale_fill_viridis_c(option = 'C') 
    })

您可以将 tempI() 视为一个知道其 return 值何时过时的函数。一旦发生这种情况(即一旦用户更改滑块) tempI 必须重新评估。因此它像一个函数一样工作。这也证明了 reactive 这个名字的合理性。

您可以了解有关反应式表达式的更多信息here