shiny app fails on shinyapps.io, data not found

Viewed 755

I have a that runs fine in locally but not on shinyapps.io. I consulted the Rstudio guidance on this point and none of the obvious problems seem present (e.g. absolute paths). The problem seems to be that the app doesn't find the data; I have checked and rechecked and am uploading the data to shinyapps.io with the code. The error in the log file is:

Warning: Error in is.data.frame: object 'dat' not found.

This is the server.R file:

library(ggplot2)

layerFit <- function(fit){
  geom_line(data = fit,
            aes(x, y), color="red",size = 1, linetype = 2)
}

dat <- read.csv("data.csv", stringsAsFactors = F, na.strings = "NA")

dat$date <- as.Date(paste0(dat$month, "-", dat$day), format = "%m-%d")
dat$time <- 1:nrow(dat)

server = function(input, output) {

  expfit <- reactive({
   dat2 <- dat[!is.na(dat[[input$variable]]),]
    mod <- lm(as.formula(paste("log(",input$variable, ") ~ time")), dat2)
    expfit <- data.frame(x = dat2$date,
                         y = exp(fitted(mod)))

    return(expfit)
  })


  output$data <- renderPlot({
    fit <- expfit()
    p <- ggplot(dat, aes(y = !!input$variable, x= date))+
      geom_point() +geom_line()+
    if(input$toggleExpFit) p = p + layerFit(fit)
    p
  })
}

And this is the ui.R file:

ui <- fluidPage(
  varSelectInput("variable", "Variable:", dat[,c("x","y")]),
  checkboxInput("toggleExpFit", label = "Exponential model", value = FALSE), 
  plotOutput("data")
)

You can create fake data like the data.csv file by:

dat <- data.frame(day  1:20, month = 1, x = rnorm(20), y = rnorm(20))

Thanks for your help.

2 Answers

As described, you could work with a global.R script.

Alternatively, you could largely keep your code as is if you remove the choices from varSelectInput(), e.g. varSelectInput("variable", "Variable:", ""). Then, in your server.R file, you could add an updateVarSelectInput() statement. That way, you could even add interactive filters over your dat variable and the choices would change accordingly. You wouldn't necessarily need a global.R file in that case.

See ?updateSelectInput for a nice example.

As suggested by A. Suliman, the solution is to put everything before the server function into a separate global.R script.

Related