This is the companion repository for the lightning talk given December 9th, 2020. YOUTUBE LINK HERE
Getting rmarkdown to work correctly is always a struggle for me, there are a lot of moving parts. Don’t be discouraged if you can’t get this repo working immediately. Keep debugging and send me a message if you get stuck.
The renv package was used to create and maintain the environment for this project. First install this package if you haven’t already
install.packages("renv")
When you open the project associated with this repo (after installing renv), it should activate the renv. Check this with
renv::status()
Next, install the dependencies needed to run this code with
renv::restore()
This project was created on Win10, with R version 4.0.2. If you install this on Linux or Mac, you may have an issue with the fonts used on R/rmarkdown/report_master.Rmd. The mainfont in the yaml header needs to be changed to a font you have installed. Ubuntu is a font option for Ubuntu-based distros. I used Calibri on my win10 machine.
On Ubuntu, you will more than likely have to install the magick++ package with an apt command, the output from renv::restore() should tell you what you need to do.
The goal here is to create parameterized (param’d) reports for a financial institution that has three branches. We want to:
- Read financial data from a SQL database
- Create various tables and charts in an rmarkdown document
- Knit the document to a pdf that can be distributed to whomever
You can run the reports from the terminal with
Rscript R/main.R
or you can run main.R from the R repl. This should place three pdfs in the /finished_reports/ folder.
Rmarkdown will knit our PDF packets and KableExtra will help us format our financial tables. Renv will help us maintain our environment and glue will be very helpful in parameterizing our reports and strings.
The data-raw/fake.R script creates fake financial data for us with the charlatan R package. Then it writes a few tables to a local SQLite db. We will ping this database in our example, but you could obviously connect to any data with this method.
Our main rmarkdown document is what I’ll call a “parent”, with several children rmarkdown files. R/rmarkdown/report_master.Rmd knits together various children rmarkdown docs located in R/rmarkdown.
We rely on the kableExtra package heavily at this stage. A good tutorial for using kableExtra with pdf output can be found here.
The last step is to iterate over the three branches in our example, and create a report for each, given the parameter: branch.
R/main.R is the file that runs our actual process. First it sources our R/setup.R file and then constructs a function to knit a pdf for each branch given the branch parameter.
If you run R/main.R, at this point you should have three pdfs in finished_reports.
Reach out to me at me[at]bradlindblad.com or my website technistema.com.