Difference from read_chunk() and source() in a Rmarkdown

Hi, guys! I have a question:

Suppose I have the script example.R and I want to run it inside a .Rmd.

example.R

## ---- chunk
1 + 1

What is the difference from:
example1.Rmd

```{r setup}
knitr::read_chunk("example.R")
``´

```{r chunk}
``´

Than:
example2.Rmd

```{r }
source("example.R")
``´

Thanks a lot!

Ps: I know that there is missing [`] on my example here. I just don't know how to put it better to see here, lol.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Hello

When using source(), all the content of the file will be evaluated from the chunk where you called source, and the output will have source("example.R") in the chunk.

When using read_chunk(), knitr will read the content labelling based on the comment, then it will use the piece of code with the correct label when used in a chunk (and not the all file at once), and in the output the code in the chunk will be the pieces of code itself.

So this is different usage. Basically, read_chunk() is useful to use in code chunk content some code that is stored in an external R file.

If you want to source a whole file content at once, while having the code chunk content being the content of the file, you can also have a look at the file chunk option

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

I let you try all that - you should see the different in the output produced.

Hope it helps

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.