how to source a file in rmarkdown located in the same RStudio project?

I have a project in Rstudio, with two files x.Rmd and y.R which has functions, etc


title: "Untitled"
date: "5/21/2020"
output:
word_document:
reference_docx: "word-styles-reference.docx"

knitr::opts_chunk$set(error = TRUE)
setwd(rstudioapi::getActiveProject())
source("y.R")

I get an error
setwd(rstudioapi::getActiveProject())

Error: RStudio not running

source("y.R")

Error: RStudio not running

Hello,

You can find the correct way for sourcing global code here, and for sourcing code in specific chunks here.

Hope this helps,
PJ

Hello,

Still is not working

setwd(rstudioapi::getActiveProject())

source("y.R", envir = knitr::knit_global())

sys.source("y.R", envir = knitr::knit_global())

Error: RStudio not running

Hi,

Here is an example that works for me (both files are in the same directory.):

File to source (test.R)

myFunction = function(x){
  x^2
}

Markdown document

---
title: "Markdown"
output: html_document
---

```{r, include=FALSE}
sys.source("test.R", envir = knitr::knit_global())
```
## Test sourced function (myFunction)

```{r echo=TRUE}
myFunction(2)
```

Output
image

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.