Bookdown: Variables across chapters (.Rmd files)

Today I realized that a variable defined in one chapter of a bookdown project cannot be called in another one.
This could, however, sometimes be helpful.
An obvious solution, which came to my mind was to define the variables inside a separate R script and source this script in both chapters (.Rmd files).
I was just wondering whether someone else has an idea about a best practice for such a case.

Creating a package with your variables, data, or functions that you need in several projects is the nicest way. And that is what packages are, really: an easy and standard way to distribute and load code and/or data (of course, you don't have to distribute your package).

Thank you, that sound's very reasonable.
When thinking of packages, I was primarily thinking of distributing code and not so much of data (and the variables which store it).

1 Like

using source('my_junk.R') to read in a script that loads the data is not unreasonable at all. Nor is a small package to do the same thing. My personal packages typically start as things I source then get upgraded to packages later. And, because I'm lazy, they often don't get turned into packages at all :slight_smile:

That makes sense since our first exposure to packages is with packages from others, and thus packages that have been distributed. So we get a biased view of what packages really are.

And creating a package with the code/data you want to re-use is a bit of upfront work. But since you asked a question about best practice, that would be it. And once it is done, you can load that code anywhere, anytime, from any project extremely easily. You don't have to worry about the paths of the files you source, etc.

Oh, I realized that I actually read your reply too quickly. Lots of packages come with data, along with functions. And there are even packages that only contain data (e.g. datasets or gapminder).