Some days ago I found a post on R-bloggers.com about Scheduling R Markdown Reports via email. The original post can be found here.

Unfortunately this article describes the sending of emails on Windows systems. So let me show you how I send R Reports on a Linux system.

Report Generation

First I need to generate the report. As I wrote last year I prefer to create pdf-reports using knitr and LaTeX.

So let’s say the report is Report.Rnw. First we have to generate a LaTeX-file:

1
2
cd some_directory
/usr/bin/Rscript -e "library(knitr); knit(\"Report.Rnw\")"

Then we need to generate the pdf-file.

1
2
3
xelatex Report.tex
# sometimes you need another xelatex run to refresh the toc.
xelatex Report.tex

Sending the email

With the unix tool mail we send the document as attachment.

1
/usr/bin/mail -r"sender@domain.com" --subject="SUBJECT" --attach=Report.pdf --to "reciptient@other-domain.com" < content-of-mail.txt

Bash script with some configuration

So let’s wrap it up and put the commands in a bash-file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/bin/bash
 
RECIPIENTS="rcpt1@domain1.com, rcpt2@domain2.com"
SUBJECT="My Subject"
 
# generation
cd some_directory
/usr/bin/Rscript -e "library(knitr); knit(\"Report.Rnw\")"
 
# sometimes you need two xelatex runs to refresh the toc.
xelatex Report.tex
xelatex Report.tex
 
# sending
/usr/bin/mail -r"sender@domain.com" --subject="$SUBJECT" --attach=Report.pdf --to "$RECIPIENTS" < content-of-mail.txt

Scheduling

Use the crontab-command to schedule the execution of this script:

1
crontab -e

Now an editor pops up to edit the crontab. Most likely it’s vi. Be sure to know how to use it. That’s out of scope of this artice. Maybe you want to take a look at this tutorial.

The following line executes the script every monday at 7 am:

1
0 7 * * 1 /path/to/the/above/script.sh