Search code examples
rdevtoolsr-packagequarto

Rendering Quarto document doesn't find .R files in package


When I'm creating a simple R package I would like to use the functions created in .R files in my test_doc.qmd file. The problem is that when rendering the qmd file the function not is found while it is created in the package. It works when I use devtools::load_all() so then I the function is found in the code chunk without running it manually in the console. I tried to create a reproducible example on this GitHub repo: https://github.com/QuintenSand/test_package

So you should first clone the repo and then try to run the qmd file:

---
title: "Test quarto doc"
format: html
editor: visual
---

## Quarto

Test if the function will be rendered:

```{r}
test_function(TRUE)
```

The function test_function is in the test_function.R file. It returns the following error when rendering the document:

processing file: test_doc.qmd
  |...................................                 |  67% [unnamed-chunk-1]


Quitting from lines 12-13 [unnamed-chunk-1] (test_doc.qmd)
Error in `test_function()`:
! could not find function "test_function"
                                                                                                            
Execution halted

But when I run devtools::load_all():

devtools::load_all()
ℹ Loading test

And the code chunk:

enter image description here

You can see it works even when the function is not in the global environment. So I was wondering how we can render the quarto documents when having .R custom functions in the document?


Solution

  • If you actually need a package then you should

    1. build the package and
    2. load the package using library() in your Quarto source.

    Assuming that the package will be called test (based on your DESCRIPTION file):

    ---
    title: "Untitled"
    format: html
    editor: visual
    ---
    
    ```{r}
    library(test)
    ```
    
    Test if the function will be rendered:
    
    ```{r}
    test_function(TRUE)
    ```
    

    Alternatively, if you only want to use a function from a specific file then you could just source the content of that file into your Quarto source.

    ---
    title: "Untitled"
    format: html
    editor: visual
    ---
    
    ```{r}
    source("test_function.R")
    ```
    
    Test if the function will be rendered:
    
    ```{r}
    test_function(TRUE)
    ```
    

    If the .R file is in a sub-directory (like in your example repository) then you'll need to include that in the path like source("R/test_function.R").