Source specific code chunks from RMarkdown


I am keeping my database connections in a separate file which I usually source at the beggining of the script (eg. source("~/R/dbConnections.R"). Would it be possible to source separate code chunks if I converted the document to RMarkdown - in order to not get my environment populated with a bunch of connections. I prefer to keep all the connections in a single file, so separate file for each connection is nogo.


I think using the config package is a good option to replace your current method.

You could also work with knitr::read_chunk:
16.3 Read multiple code chunks from an external script (*) | R Markdown Cookbook (

Instead of source("~/R/dbConnections.R") you would call knitr::read_chunk("~/R/dbConnections.R") and then call your connections like this (if you called your chunks con-a, con-b...):

```{r, con-a}
```{r, con-b}
1 Like

Thanks. I am using config just for storing connection details inside my dbConnections script. I will look into it a bit more.

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.