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.

1
  • 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 with sample input and desired output that can be used to test and verify possible solutions. Commented Oct 25, 2020 at 20:50

1 Answer 1

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") ``` 
Sign up to request clarification or add additional context in comments.

4 Comments

RStudio’s behaviour is very intentional, and your suggested solution is strongly discouraged.
@KonradRudolph Is it discouraged because it's exposing the global env if so I changed the envir param
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).
he can directly source the file inside the rmd tbh

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.