闪亮的R:实现滑块输入

时间:2016-11-29 09:17:25

标签: r shiny

我有这个数据集here,我想创建一个简单的滑块输入,其中国家的相应平均温度将通过改变年份而改变。到目前为止,我已经写了这个。我想预测加拿大从1743年到2013年的平均温度。我应该如何实现这一目标呢?

ui.R

fluidPage(
  verticalLayout(
    titlePanel("Russian Average Temperature"),
    plotOutput("plot1"),
    wellPanel(
      sliderInput("Year", "Timeline", 1743, 2013,
                  value = 0, step = 1)
    )
  )
)

server.R

library(shiny)
library(dplyr)
library(tidyr)
library(ggplot2)

data <- read.csv("..\\GlobalLandTemperatures\\GlobalLandTemperaturesByState.csv",
                 fileEncoding = "UTF-8")

function(input, output) {

  data  %>%
    filter(Country=="Canada")  %>%
    separate(col = dt, into = c("Year", "Month", "Day"), convert = TRUE) ->cCanada
  cCanada<-na.omit(cCanada)

  cCanada %>% 
    filter(Year>1743) %>%
    group_by(Year) %>% 
    summarise(Temp = mean(AverageTemperature)) ->cCanAvgTemp

  output$plot1 <- renderPlot({
    plot(x = Year, y = AverageTemperature)
  })
}

1 个答案:

答案 0 :(得分:0)

您需要创建反应式数据集,因此它看起来像这样:

   data <- reactive({
     if(!is.null(input$Year)){
       data<-cCanAvgTemp %>%
         filter(cCanAvgTemp[ ,Year] >= input$Year[1])
     }
     data
   })

 output$plot1 <- renderPlot({
    plot(data=data(),x = Year, y = Temp)
  })

[编辑] 完整代码:

library(shiny)
library(dplyr)
library(tidyr)
library(ggplot2)

data <- read.csv(".../data.csv")

ui <- fluidPage(
  verticalLayout(
    titlePanel("Russian Average Temperature"),
    plotOutput("plot1"),
    wellPanel(
      sliderInput("Year", "Timeline", 1743, 2013,
                  value = 0, step = 1)
    )
  )
)

server <- function(input, output) {

  data  %>%
    filter(Country=="Canada")  %>%
    separate(col = dt, into = c("Year", "Month", "Day"), convert = TRUE) ->cCanada
  cCanada<-na.omit(cCanada)

  cCanada %>% 
    filter(Year>1743) %>%
    group_by(Year) %>% 
    summarise(Temp = mean(AverageTemperature)) ->cCanAvgTemp

  data2 <- reactive({
    data <- as.data.frame(cCanAvgTemp)
    if(!is.null(input$Year)){
      data<-data %>%
        filter(data$Year >= input$Year[1]) #to get value for choosen year change >= sign to ==
    }
    data
  })

  output$plot1 <- renderPlot({
    data2 <- data2()
    ggplot(data= data2, aes(x = Year, y = Temp)) + geom_line()
  })
}

shinyApp(ui = ui, server = server)

结果:

enter image description here