Using parameters in Rmarkdown
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Nothing new or original here, just something that I learned about quite recently that may be useful for others.
One of my more “popular” code repositories, judging by Twitter, is – well, Twitter. It mostly contains Rmarkdown reports which summarise meetings and conferences by analysing usage of their associated Twitter hashtags.
The reports follow a common template where the major difference is simply the hashtag. So one way to create these reports is to use the previous one, edit to find/replace the old hashtag with the new one, and save a new file.
That works…but what if we could define the hashtag once, then reuse it programmatically anywhere in the document? Enter Rmarkdown parameters.
Here’s an example .Rmd file. It’s fairly straightforward: just include a params:
section in the YAML header at the top and include variables as key-value pairs:
--- params: hashtag: "#amca19" max_n: 18000 timezone: "US/Eastern" title: "Twitter Coverage of `r params$hashtag`" author: "Neil Saunders" date: "`r Sys.time()`" output: github_document ---
Then, wherever you want to include the value for the variable named hashtag
, simply use params$hashtag
, as in the title
shown here or in later code chunks.
```{r search-twitter} tweets <- search_tweets(params$hashtag, params$max_n) saveRDS(tweets, "tweets.rds") ```
That's it! There may still be some customisation and editing specific to each report, but parameters go a long way to minimising that work.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.