woshitom woshitom - 17 days ago 5
R Question

Shiny with flexdashboard, dataframe as variable

Using shiny within Flexdashboard I want to plot and display a dataframe where this dataframe is a variable from an input in my sidebar:

Inputs {.sidebar}
-----------------------------------------------------------------------

```{r}
selectInput("df", label = h3("Select df"), choices = list("january" = "df1", "february" = "df2"))
```


I'm then plotting and displaying my dataframe inside a tabset:

Row {.tabset}
-----------------------------------------------------------------------

### Plot
```{r}
renderPlot({
plot(fread(paste("/Users/woshitom/Desktop/shiny/",input$df,".csv",sep="")),type="o", col="blue")
})
```

### Data
```{r}
renderTable(fread(paste("/Users/woshitom/Desktop/shiny/",input$df,".csv",sep="")))
```


As you can see I'm loading 2 times my csv:

fread(paste("/Users/woshitom/Desktop/shiny/",input$df,".csv",sep=""))


Instead I'd like to store it in a variable:

my_df <- fread(paste("/Users/woshitom/Desktop/shiny/",input$df,".csv",sep=""))


But when I do so I'm getting the following 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.)


Any idea how i should store this dataframe?

Answer

Shiny inputs should be used inside render functions, observers or reactives. This is why you are getting the error. In your case since you want to store the result in a variable the way to go is to create a reactive variable with reactive(). This is the soltution:

my_df <- reactive({fread(paste("/Users/woshitom/Desktop/shiny/",input‌​$df,".csv",sep=""))}‌​)