I am new to using Shiny with R. I have to develop a web app to display graphs based on the range of years. Shiny server has to take inputs from ui (starting year and ending year) and make calculations and plot the outputs. I have written R script to make a vector named years with the different years in the range selected and bind it to a data frame. Then, its followed by adding new calculated columns to the table and plotting different columns. This is the code
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "startyear",
label = "Choose starting year",
value = 25, min = 2016, max = 2050),
sliderInput(inputId = "endyear",
label = "Choose ending year",
value = 25, min = 2016, max = 2050),
plotOutput("plot1"),
plotOutput("plot2"),
plotOutput("plot3")
)
server <- function(input, output) {
years <- reactive({(input$startyear:input$endyear)})
sample <- data.frame(years)
sample$timestepdays <- (sample$years-min(sample$years))*365
sample$timestep <- (sample$years-min(sample$years))
sample$pop <- sample$timestepdays *500 +839000
sample$no_of_trips <- sample$pop*4.4045
sample$NE <- sample$no_of_trips*0.00000003+0.3738
sample$Delta_VE_logit <- sample$timestep*(-0.149) +5
sample$Delta_VE <- (exp(sample$Delta_VE_logit)/(exp(sample$Delta_VE_logit)+1))*(1-0.5)+0.5
sample$VMT <- 7.3 * sample$no_of_trips
sample$ER_per_mile <- sample$Delta_VE * sample$NE
sample$CO2 <- (sample$ER_per_mile * sample$VMT ) /10000
output$plot1 <- renderPlot({lines.default(sample&years,sample$population)})
output$plot2 <- renderPlot({lines.default(sample&years,sample$no_of_trips)})
output$plot3 <- renderPlot({lines.default(sample&no_of_trips,sample$NE)})
}
shinyApp(ui = ui, server = server)
I am getting the following errors
Warning: Error in as.data.frame.default: cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame
Stack trace (innermost first):
40: as.data.frame.default
39: as.data.frame
38: data.frame
37: server [C:/Users/R-Jaikumar/Downloads/shiny-quickstart-1/downloads/code/01-template.R#17]
1: runApp
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame
reactive({}), you need to refer to it asvariable()from then on. Sosample <- data.frame(years)should besample <- data.frame(years()). - Baltersample, that should be a reactive but not a data.frame - Sean Lin