Evaluation error: Operation not allowed without an active reactive context

HI everybody, I've added a date filter to my Shiny App. Now I want to filter the data frame dynamically according to the date input.

I tried this as follows in die ui.R:

fluidPage(
      selectInput(
        "analysis_period",
        "analysie period:",
        c(
          "Last Year" = "LY",
          "Past 90 days" = "ND",
          "Past 30 days" = "TD",
          "Last Week" = "LW"
        )
      )
     )

In my server section I have:

>date_input <- reactive({
if (input$analysis_period== "NT") {
  as.Date(Sys.time()) - 90
}

else if (input$analysis_periodm == "DT") {
  as.Date(Sys.time()) - 30
}

else if (input$analysis_periodum == "LW") {
  as.Date(Sys.time()) - 7
}

else if (input$analysis_period == "LY") {
  m = as.POSIXlt(as.Date(Sys.time()))
  m$year = m$year - 1
  m
}

Then I want to load the data frame and filter it using the filter:

 data2 = data[, c('A', 'B', 'C')]
  data2 <- filter(data2, date_input())

But when I start the app I always get the error:

Error in filter_impl(.data, quo) : 
Evaluation error: Operation not allowed without an active reactive context. 
(You tried to do something that can only be done from inside a reactive 
expression or observer.).

What am I doing wrong here? Thanks!!

Since your reprex is not executable, I am not able to reproduce your error. However, it could be the case that you are trying to access a reactive element inside the Server function but outside of any Shiny reactive functions. Check this SO answer. Wrap your filter component within a reactive and it should work.

1 Like

I think the problem is exactly as written, you try to use date_input() outside a reactive context. You could try to wrap date_input() in isolate(). But then, of course, data2 will not be automatically updated when input$analysis_period and thereby date_input() changes.

Cheers
Steen

Your code looks like this:

 data2 = data[, c('A', 'B', 'C')]
  data2 <- filter(data2, date_input())

If date_input() changes, there is no way that data2 can automatically update, even though that is probably your intention. Therefore, this code has a bug, and that error message is our way of telling you that: you need to introduce either a reactive expression (to calculate a derived value) or an observer (to perform an action). In this case, data2 is a derived value. The correct code looks like this:

data2 <- reactive({
  df <- data[, c("A", "B", "C")]
  # I'm pretty sure you don't mean this. Maybe date == date_input()?
  df <- filter(df, date_input())
  df
})

And everywhere you were planning to use data2, use data2() instead.

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.