Using parameters in Rmarkdown

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 mini...
Source: What You're Doing Is Rather Desperate - Category: Bioinformatics Authors: Tags: programming statistics automation reports rmarkdown Source Type: blogs