johnalias91 - 6 days ago 6
R Question

# Shiny R: Implement Slider Input

I have this dataset here and I would like to create a simple Slider Input where the respective average Temperature of the country will change by changing the year. So far I have written this. I want to project the average Temperature of Canada throughout the years from 1743 till 2013. How should I proceed in making this happen?

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)

fileEncoding = "UTF-8")

function(input, output) {

data  %>%
separate(col = dt, into = c("Year", "Month", "Day"), convert = TRUE) ->cCanada

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

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

You need to create reactive dataset, so it will look like that:

``````   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)
})
``````

[EDIT] Full code:

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

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

server <- function(input, output) {

data  %>%
separate(col = dt, into = c("Year", "Month", "Day"), convert = TRUE) ->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)
``````

Result:

Source (Stackoverflow)