Search code examples
shinyr-markdownchunks

Shiny and RMarkdown: Rendering multiple chunks


I would like to create a Shiny-RMarkdown app which allows uploading own datasets. Datasets sometimes not only affect one chunk which can be re-rendered by renderPlot() (or similar) but sometimes two or more chunks. See the following example:

---
title: Render multiple chunks
output: html_document
runtime: shiny
---

```{r echo=FALSE}
library(shiny)
fileInput('file1', 'Choose your own CSV File instead of provided 
data',accept=c('text/csv', 'text/comma-separated-values,text/plain', 
'.csv'))

go1<-reactive({
  dpath <- "CurrentBiologyData.txt"
  if(!is.null(input$file1)){
     dpath <- input$file1$datapath
  }
  CB.dat <- read.table(dpath, header = TRUE)  #choose 'CurrentBiologyData.txt'
  plot(CB.dat)
})
```

```{r echo=FALSE}
renderPlot({
      go1()
})
```

```{r}
   renderPlot({
   print(CB.dat)
   }) 
```

So I have three chunks which are affected if I upload a new dataset. The problem is that the third chunk does not see CB.dat which is filled in the first chunk:

Error: Object 'CB.dat' not found

Any ideas how I can make that work?


Solution

  • Applying to your example what I meant in my comment

    Put the file reading in a reactive then use it wherever you need it

    ---
    title: Render multiple chunks
    output: html_document
    runtime: shiny
    ---
    
    ```{r echo=FALSE}
    library(shiny)
    fileInput('file1', 'Choose your own CSV File instead of provided 
    data',accept=c('text/csv', 'text/comma-separated-values,text/plain', 
    '.csv'))
    
    CB.dat<-reactive({
      dpath <- "CurrentBiologyData.txt"
      if(!is.null(input$file1)){
         dpath <- input$file1$datapath
      }
      read.table(dpath, header = TRUE)  #choose 'CurrentBiologyData.txt'
    })
    ```
    
    ```{r echo=FALSE}
    renderPlot(plot(CB.dat())
    ```
    
    ```{r}
    renderTable(CB.dat())
    ```