0

I saw someone ask a similar question to this but did not have a conclusive answer... I am trying to knit an rmd file to html and am using a function that I wrote in a .R file. I get an error saying the function can not be found etc.

Also just a note that when I run the chunk of code that the function is called for, it works. Just an error when knitting.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
neuroandstats
  • 124
  • 11
  • Is your function defined in the rmd file itself? When you knit an rmd file, it runs in a new R session. Everything needed to knit the document needs to be contained in the document itself. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 25 '20 at 20:50

1 Answers1

2

This is because you're using the knit button in Rstudio which creates a new session then executes rmarkdown::render, in order to use locally defined function you have to call rmarkdown::render from the console.

Note: that this will block the console until the .Rmd file is rendered.

my.envir <- new.env(parent=baseenv())
local({
  f <- function() { ... }
  #...
}, my.envir)
# OR source your file directly into my.envir
source("ur.file.R", local = my.envir)
rmarkdown::render(input, # path to the .Rmd file
   output_format = "html_document", # output type if not set it'll use the first one found in the yaml header
   output_file = NULL, # name of the output file by default it will be the 
       # name of the .Rmd with the extension changed
   clean = TRUE,  # set to FALSE if you want to keep intermediary files
   envir = my.envir, # this where the magic happens
       # if you don't want to modify the global env you can create your own environment and add the function to it
   quiet = FALSE # set to TRUE if you want to suppress the output
)

EDIT following @KonardRudolph's comments:

It's better to source your file into the rmd itself, as the main goal of Rmarkdown is reproducible research.

```{r setup, include=FALSE}
.
.
.
source("path/to/file.R")
```
Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21
  • RStudio’s behaviour is very intentional, and your suggested solution is strongly discouraged. – Konrad Rudolph Oct 25 '20 at 20:59
  • @KonradRudolph Is it discouraged because it's exposing the global env if so I changed the envir param – Abdessabour Mtk Oct 25 '20 at 21:05
  • 3
    The issue is that it makes knitting depend on some external state, and thus unreproducible. This would also be true if you used a different environment. It really needs to be a *clean* environment (and ideally an entirely clean *session*, to be shielded from other side-effects, such as different loaded packages). – Konrad Rudolph Oct 25 '20 at 21:07
  • he can directly source the file inside the rmd tbh – Abdessabour Mtk Oct 25 '20 at 21:09