6

Wondering how to include snippet code from external file into document.

  1. The following code using knitr::read_chunk() works fine however, depends on .

    knitr::read_chunk("Ch02.R")
    
  2. The following code using code runs without any error but does not work as expected.

    #| eval: true
    #| output: false
    #| file: Ch02.R
    

Wondering if there is any alternative in for knitr::read_chunk().

MYaseen208
  • 22,666
  • 37
  • 165
  • 309

3 Answers3

5

Option 1: include

If you want to include other code snippets, you could only use qmd files when using include:

Computational includes work only in .qmd files

Let's create a simple qmd file called create_dataframe.qmd which add a column to mtcars:

---
title: "Create dataframe"
---

```{r}
# Create data file 
mtcars$new_col = sample(c(0,1), nrow(mtcars), replace = TRUE)
```

Now you can include that file in your main.qmd file like this:

---
title: "Document"
---

{{< include create_dataframe.qmd >}}

Let's check if extra columns is created:

```{r}
# View dataframe
head(mtcars)
```

Output:

enter image description here

As you can see, the column created in the create_dataframe.qmd file is now in your main file.


Option 2: file in chunk

You could also the file option in your chunk like this. You have to make sure it evaluates the code using eval like this:

---
title: "Document"
---

Let's check if extra columns is created:

```{r}
#| echo: true
#| eval: true 
#| file: create_dataframe.R
```

```{r}
# View dataframe
head(mtcars)
```

Output:

enter image description here

As you can see the new column is also in the dataframe.

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Thanks for your help. What I got from your answer is that `knitr::read_chunk("Ch02.R")` is only the solution to include `R` snippet code from external file into `Quarto` document. – MYaseen208 Mar 07 '23 at 14:57
  • Hi @MYaseen208, Please see my edited answer with another option! – Quinten Mar 07 '23 at 17:04
1

You can use either source to just run the valid R code or use file to include the script as a chunk and evaluate

---
title: "Untitled"
format: html
---

## Include will interpret the content as markdown:

{{< include Chu1.R >}}


## Source will evaluate:

```{r}
#| echo: false
source("Chu1.R")
```


##  file will echo and evaluate

```{r,file = "Chu1.R"}

```

enter image description here

user12256545
  • 2,755
  • 4
  • 14
  • 28
-1

You can use the include directive.

For example,

{{< include Ch02.R >}}

More details at https://quarto.org/docs/authoring/includes.html

Raniere Silva
  • 2,527
  • 1
  • 18
  • 34