简体   繁体   中英

How to load a file (selected with shiny widget) only once but use multiple times in R-Markdown document with Shiny runtime

Using the fileInput widget I set the path to a file in my R-markdown document. The path is leading to a large file. Content of this file is required at several sections in the document. So far I load the file at each section where it is required. As it takes some time for the file to load, changing the file results in quite some loading time. I would prefer to load the file only once after the path is changed.

The following minimal example shows my current implementation where the file is loaded at each section it is used.

--- output: html_document runtime: shiny ---

library(kableExtra)
knitr::opts_chunk$set(echo = TRUE)
 fileInput("file", label = h3("File input"))
 renderUI({
   loaded_file <-read.csv(input$file$datapath, sep = ";", header = T)
   paste(loaded_file[1,2])
 })
 renderUI({
   loaded_file <-read.csv(input$file$datapath, sep = ";", header = T )
   HTML(kable(loaded_file))
 })

If you load the file into a data frame as a separate reactive expression, and then reference that expression in all the relevant UIs, I believe that will accomplish what you need. Here's a small example:

---
output: html_document
runtime: shiny
---

```{r load_file}
library(kableExtra)
library(dplyr)
knitr::opts_chunk$set(echo = TRUE)

fileInput("file", label = h3("File input"))
loaded_file_test = reactive({
  if(is.element("datapath", names(input$file))) {
    print("loading file now...")
    read.csv(input$file$datapath, sep = ",", header = T)
  }
})
```

```{r first_ui}
renderUI({
  HTML(kable(loaded_file_test() %>% head(10)))
})
```

```{r second_ui}
renderUI({
  HTML(kable(loaded_file_test() %>% head(10)) %>% kable_styling())
})
```

When I run the document, "loading file now..." is printed just once. I interpret that to mean the file is getting loaded only once (although I'm happy to be corrected by users with a better handle on reactivity in Shiny).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM