Search code examples
rshinydashboardflexdashboard

How to use shiny input variables in a global variable in flexdashboard


I have a problem that I have to take the select input values and use in a function, but I can't call the function in multiple Renders (plot, print, table) because it's a costly function. With the shiny input, I would like to create a Filtered data and other variables too. The error method I get is the:

Operation not allowed without an active reactive context.

This is just a simple example.

---
title: "TITLE"
output: 
  flexdashboard::flex_dashboard:
    orientation: row
    vertical_layout: fill
    theme: flatly
runtime: shiny
---


```{r global, include=FALSE}
require(flexdashboard)
require(ggplot2)
df <- data.frame(year = c("2013", "2014", "2015", "2013", "2014", "2015", "2013", "2014", "2015"),
                 cat = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
                 freqA = c(100, 100, 110, 80, 80, 90, 90, 90, 100),
                 freqB = c(50, 50, 55, 40, 40, 45, 45, 45, 50))

plus <- function(a,b){
  return(a + b)
}


```


Column {.sidebar}
-----------------------------------------------------------------------



```{r}

selectInput("a","select A:", c("freqA","freqB"))
selectInput("b","select B:", c("freqA","freqB"))




```

Column {data-width=350}
-----------------------------------------------------------------------

### Itens mais frequentes

```{r}

sum <- plus(df[,input$a], df[input$b])


```

### Chart C

```{r}

```


Column {data-width=650,data-high=10}
-----------------------------------------------------------------------

### Relações

```{r}

```

Solution

  • It is just the way the error message says: you can only use reactives (such as input elements) in reactive expressions.

    This is because every time the input elements change, the output must be rerendered, and you can only do this in reactive context.

    Edit:

    1. You can create a reactive variable in an R chunk:

    The contents will be cached, so it only runs once, even if you will use it in different chunks:

    ```{r}
    
    sum <- reactive( {
      plus(df[,input$a], df[input$b])
    })
    
    ```
    
    1. After this, you can use the reactive expression called sum within render functions, such as renderPrint:

    Note that you can access reactives just like functions (i.e.: sum())

    ### Itens mais frequentes
    
    ```{r}
    renderPrint( {
      sum()
    })
    ```
    

    enter image description here