rapport  an R templating system


Introduction

rapport is an R package that facilitates creation of reproducible statistical report templates. Once created, rapport templates can be exported to various external formats: HTML, LaTeX, PDF, ODT, DOCX etc. The appearance of the page you are just reading is similar to a ‘rapported document’. Apart from R, all you need to know to start writing your own templates is Pandoc’s markdown syntax, and some rapport conventions that allow the reproducibility of the template.

Several predefined templates come bundled with default rapport installation, and their number will increase in future releases. Of course, we strongly encourage you to write your own templates, and/or customise the ones that are shipped with default package installation.

For a brief introduction to rapport, run:

demo(rapport, ask = FALSE)

Frequently Asked Questions

What does “rapport” mean?

Actually a lot of stuff:

* Stewart, Dorothy (1998). Gower handbook of management skills. Gower Publishing. p. 282. ISBN 0566078899

Who is developing this package?

Members of the rapport development team are painstakingly procrastinating on this project, to the utmost limits of endurance. Feel free to contribute and help us localising it!

Why should I prefer rapport over Sweave, brew, knitr and the like?

Short answer: you should not.

Long answer: you should not… oftentimes… especially if you already have an efficient development work flow. But rapport is a bit different from the other popular dynamic report frameworks in R: Sweave, brew, or even knitr. With those nifty tools you can easily embed R code and R output in TeX, PDF, HTML and other formats, which is a common practice in advanced R users.

rapport has a similar goal: to use R to generate dynamic, reproducible templates, which can be easily exported to various external formats, providing (hopefully) nicely formatted template elements, such as tables, graphs or in-line expressions. You may get an impression that rapport is n00b-friendly interface to statistical report creation, but from our POV, it’s just a convenient way of dealing with repetitive tasks.

rapport relies on some predefined/custom templates, which can be easily ran against any dataset and with user-defined input specifications . Don’t forget: custom templates are easy to write!

OK, you got me. How can I use this package?

Read sections on usage and/or writing custom templates.

I found a bug. What should I do?

Please join our discussion list or file an issue on Github tagged as bug!

I have a really cool idea about this package. Are you interested?

Hell yeah! Please join our discussion list or file an issue about your idea on Github tagged as feature, we will be really interested to check it out.

Can I use this package for academic/commercial/any other purpose?

Of course, with some limitations: see license terms for details.

How can I use my custom templates without always specifying the full path and name of the templates?

Check out rapport.path and rapport.path.add. If you add the paths of the directories holding your custom templates, rapport and any related function would easily find it just like you would use a package bundled template. So if you have e.g. mytemplate.rapport in /tmp, adding that to the list of custom paths like rapport.path.add('/tmp'), you can easily call rapport('mytemplate', ...). You don’t even have to include the extension of the file (unless it ends with something other than rapport).

It would be a good practice to add a call to rapport.paths.add(...) to your .Rprofile, which would be evaluated on each R session startup.

Why do you write such complex templates? Why not including those in helpers like rp.anova?

It is based on a theory behind rapport: you can define a function at any part of your template and use it, or just load any library which is installed on your system - even your own, local packages. You might even include a source command in your local template, but bear in mind that this template will not be able to run on other computers!

OK, I understand, but I have a really handy function which should be added to rapport!

We’d be glad to incorporate it in our package, please file an issue about your idea on Github tagged as feature. Or write your own package submitted to CRAN and please attract our attention to add that package to our required or suggested package list.

HTML template exports have ugly fonts in Firefox, but not in other browsers. What’s the catch?

Actually, it’s not a rapport bug, rather a Firefox feature. Type about:config in Awesome Bar™ and search for following property:

security.fileuri.strict_origin_policy

Set it to false (by double-clicking on it) and refresh the page (you may want to bypass the browser cache, too: use Shift + click on Refresh button, or Ctrl+Shift+R). Behold the pretty fonts! See an answer that solved this strange behaviour.

I’m trying to produce those fancy HTML tables you have in rapport. Any tips on how to do that? (Q of Roman Luštrik)

Sure, just put a piece of code that returns a data.frame object in a chunk, and it will be converted to HTML table once you export it. Put something like this in your .rapport file:

<%=
rp.desc("edu", "student", c(min, max, mean, sd), ius2008)
%>

and run rapport.html(<file path>, <data>, <inputs>).

Installation

We’ll start with a brief reminder: make sure that you have Pandoc installed, and then proceed with package installation.

Starting from v.0.2 rapport is hosted on CRAN, so you can install it by calling:

install.packages('rapport')

Or you can grab the latest build from GitHub via nifty function from devtools package:

library(devtools)
install_github('rapport', 'rapporter')

You can also download sources in a zip or tarball archive and build package manually. To do so, please extract archive to an empty directory and run the following commands:

R CMD build rapport
R CMD INSTALL <path to .tar.gz file>

If you’re running R on Windows, you need to install Rtools. Once you have installed it, you can either try out the install_github() approach or install package manually by downloading tarball sources and issuing following commands in the command prompt:

R CMD build --binary <path to .tar.gz file>
R CMD INSTALL <path to .zip file>

In order to export rapport templates to HTML, ODT, DOCX or PDF, please install pandoc.

And an up-to-date version of pander (an R markdown writer) installed from GitHub is also really advocated:

library(devtools)
install_github('pander', 'rapporter')

Usage

After installing, load the package:

library(rapport)

The most obvious goal of this package is to easily reproduce a report by providing a custom dataset.

rapport has some predefined templates distributed with the package. These files can be found in templates directory of the package with rapport extension. Getting a list of all available templates is easy:

> rapport.ls()
 [1] "AnalyzeWizard.rapport"               "ANOVA.rapport"                       "BartlettsTest.rapport"               "BrownForsythTest.rapport"           
 [5] "Correlation.rapport"                 "Crosstable.rapport"                  "Descriptives.rapport"                "Example.rapport"                    
 [9] "FactorAnalysis.rapport"              "FTest.rapport"                       "GenerateBeta.rapport"                "GLM.rapport"                        
[13] "HierarchicalClusterAnalysis.rapport" "HomogeneityCrosstable.rapport"       "KMeansCluster.rapport"               "KolmogorovSmirnovTest.rapport"      
[17] "KruskalWallisTest.rapport"           "LinearRegression.rapport"            "MDS.rapport"                         "Minimal.rapport"                    
[21] "NormalityTest.rapport"               "OutlierTest.rapport"                 "PCA.rapport"                         "TTestOneSample.rapport"             
[25] "TTestTwoSample.rapport"              "WilcoxonTest.rapport"       

Examples

If you, find, say Minimal.rapport promising, you can check it out by calling rapport.example function which prints out the examples specified in the template, prompting you to choose one from the list:

> rapport.example('example')
Enter example ID from the list below: 

(1)	rapport("Minimal", ius2008, var='leisure') 
(2)	rapport("Minimal", ius2008, var='leisure', desc=FALSE) 
(3)	rapport("Minimal", ius2008, var='leisure', desc=FALSE, histogram=T) 
(all)	Run all examples 


Template ID>

After you typed in a template ID (1, 2, 3 or all), press ENTER key to see it in action. For example, running the first example of Minimal template returns (which can be called like rapport.example('Minimal', 1) too):

# Début


Hello, world!

I have just specified a *Variable* in this template named to **leisure**. The label of this variable is "Internet usage in leisure time (hours per day)".

And wow, the mean of *leisure* is _3.199_!

By checking out the [sources of this template](https://github.com/rapporter/rapport/blob/master/inst/templates/Minimal.rapport), you could see that we used all `BRCATCODE`s above from `brew` syntax. `BRCODE` tags are useful when you want to loop through something or optionally add or remove a part of the template. A really easy example of this: if `desc` input equals to `TRUE`, then the resulting report would have that chunk, if set to `FALSE`, it would be left our.

## Descriptive statistics

--------------------------------------------------------
Min.   1st Qu.   Median   Mean   3rd Qu.   Max.   NA's  
------ --------- -------- ------ --------- ------ ------
0.000  2.000     3.000    3.199  4.000     12.000 37    
--------------------------------------------------------

The 5 highest values are: _12_, _12_, _10_, _10_ and _10_.

What was done here? We have executed a simple analysis on the leisure variable found in ius2008 (package bundled) dataset. This simple template only returned a local greeting, the name and the label of the given variable, alongside a variable’s summary and 5 highest values.

As you could see in the examples there are some other parameters of this template besides data and var, for example: desc and hist. In order to, get some info on the template, issue following command:

> rapport.info('Minimal')

`Minimal template`

 by Gergely Daróczi

 This template demonstrates the basic features of rapport. We all hope you will like it!
 
 packages:	lattice, xtable
 
 Examples: 
 rapport("Minimal", ius2008, var='leisure') 
 rapport("Minimal", ius2008, var='leisure', desc=FALSE) 
 rapport("Minimal", ius2008, var='leisure', desc=FALSE, histogram=T) 

Input parameters 

 "var" (Variable)  *required
  A numeric variable.
   - standalone:  no
   - length:		exactly 1 vector

 "desc" (Descriptives)
 Table of the descriptive statistics
   - class:  	logical
   - standalone:	yes
   - value:		~
   
 "histogram" (Histogram)
 Histogram
   - class:    logical
   - standalone:	yes
   - value:		~
   

Okay, we have seen the examples before, but new information appears now too:

These latter shows exactly what we were looking for which can be returned by rapport.info('Minimal', meta = F) command too without meta information.

There we can see that four parameters can be provided. var is the name of the variable we want to analyze, we can set desc to FALSE instead of the default value TRUE not to print descriptive statistics and we can instruct the template to return a histogram too (see: hist parameter).

Let’s run the third example:

> rapport("example", ius2008, var='leisure', desc=FALSE, histogram=T)

# Début


Hello, world!

I have just specified a *Variable* in this template named to **leisure**. The label of this variable is "Internet usage in leisure time (hours per day)".

And wow, the mean of *leisure* is _3.199_!

**For more detailed statistics, you should have set `desc=TRUE`!**

By checking out the [sources of this template](https://github.com/rapporter/rapport/blob/master/inst/templates/example.rapport), you could see that we used all `BRCATCODE`s above from `brew` syntax. `BRCODE` tags are useful when you want to loop through something or optionally add or remove a part of the template. A really easy example of this: if `desc` input equals to `TRUE`, then the resulting report would have that chunk, if set to `FALSE`, it would be left our.

## Histogram

For demonstartion purposes you can find a histogram below:

![A nice histogram](plots/rapport-Minimal-1-1.png)

Here instead of the known rapport.example we used directly rapport which takes the above described input parameters. As you can see the descriptive statistics table is gone, instead we got a histogram. Or at least a path to a png file - which holds that image. You can find that file after running the above command (not exactly on the same path - see ?tempfile for details) on your local machine and check it out. We have attached that here.

Well, this is a quite rough way of checking out plots generated in a template :)

Export

There are a lot easier ways for that:

Please find the HTML exported versions of the examples of Minimal.rapport here or run on your machine:

rapport.export(rapport.example('Minimal', 'all'))

Which will return the above linked HTML with all examples of Minimal.rapport. Well, not exactly the same :)

Were you aware of the change in the second line which holds the name of the useR? This is set to rapport package team @ https://github.com/rapporter/rapport in our deploying system and set to undefined by default. It might be a good idea to set this to custom strings on all users’ machine, which are hold in options().

Set your name and e-mail address:

options('rapport.user'  = 'userR')

And rerun the following commands to see the changes. For other settings in rapport.export please check out the docs.

If you would like to resize/alter the dimensions of generated images in the exported reports, a nice way of doing this is like:

If you would export several rapport object at once, you can do that by combining those to a list, see rapport.export (especially the examples) for more details.

There are a bunch of other helper functions in rapport to deal with templates. As most starts with rapport prefix (except for the main rapport function), we can easily list them by typing rapport. and pressing TAB twice:

> tpl.
tpl.body          tpl.example       tpl.info          tpl.list          tpl.paths         tpl.paths.remove  tpl.rerun         
tpl.check         tpl.export        tpl.inputs        tpl.meta          tpl.paths.add     tpl.paths.reset  

By this method you might not find all handy functions, for example rapport.html and rapport.odt which are simple wrappers around rapport and rapport.export. Just use these functions you would use rapport and get a nifty HTML/odt output directly. For example:

rapport.html('example', ius2008, var = 'leisure')

Other functions

As you might have seen there are several general options in rapport which can be as handy as the funtions used while rapporting. Above we have set the username, which affects the result of all run templates. Please see the (almost) full list of available options below:

And after all, do not forget to check out other templates of this package too or even write/translate your own templates! :)

Bundled templates

rapport comes bundled with several report templates, and we hope that their number will increase in succeeding releases. To list all available templates, issue the following command: tpl.list(). These package bundled templates are:

Please find below a detailed description about each with sample outputs of those in R console, HTML, odt and pdf too.

ANOVA.tpl

BartlettsTest.tpl

BrownForsythTest.tpl

Correlation.tpl

Crosstable.tpl

Descriptives.tpl

FactorAnalysis.tpl

FTest.tpl

GenerateBeta.tpl

GLM.tpl

HierarchicalClusterAnalysis.tpl

HomogeneityCrosstable.tpl

KMeansCluster.tpl

KolmogorovSmirnovTest.tpl

KruskalWallisTest.tpl

LinearRegression.tpl

MDS.tpl

NormalityTest.tpl

OutlierTest.tpl

PCA.tpl

TTest.tpl

WilcoxonTest.tpl

Writing templates

Writing a custom rapport template or modifying an existing one is not trickier than writing an ordinary statistical report. It requires some basic R skills, and a familiarity with rapport input specifications that we’re about to cover thoroughly. Of course, sophisticated reports would require more proficiency in R.

Input Header

Recent changes

As of version 0.50, rapport is using the new header specification that relies solely on YAML syntax. The old syntax is deprecated, though kept in the package for backwards compatibility.

In order to define a valid rapport template, you’ll have to specify some info at the beginning of the document, in the so-called template header. The header itself is nothing but a YAML syntax placed within custom HTML comment tags: <!--head and head-->. It consists of metadata and inputs sections defined under meta and inputs YAML keys, respectively.

Template metadata

Template metadata can contain following fields:

If you’re familiar with the package development in R, you’ll probably find this specification similar to the DESCRIPTION file. Here’s an example of metadata section:


meta:
  title: Custom template
  author: John Doe
  description: Just a custom template
  packages:
	- lme4
  - nortest
	- ggplot2
  example:
  - rapport("custom-template", mtcars, x = "wt")
	- rapport("custom-template", mtcars, x = c("mpg", "hp"))

As you can see, it depends on lme4, nortest and ggplot2 packages, and it has 2 example calls to rapport.

Just a reminder about the technical details: One should not forget to type in the accurate number of the ‘spaces’ in the beginning of the lines! Before each fields two ‘spaces’ are required, next to them the exact packages and the examples have a hyphen and an other ‘space’ in their front.

Template inputs

The template inputs are probably the most important feature of rapport. By using the template inputs, you can match a dataset variable or custom R object and assign it to a symbol in a template evaluation environment. That way you can use given input’s name throughout the template. Since the version 0.50, we wanted to make inputs more familiar to R users, so we ditched previous input definition syntax as it was inconsistent with R conventions. New input specification relies on R class system and resembles all important methods and/or attributes of R objects.

Template inputs can be divided into two categories:

General input attributes

Following options are available for all inputs:

It worth to note, that the inputs with the possible outcome of a logical value (required, standalone) can be set with the TRUE/FALSE and the yes/no options as well.

Class-specific attributes
character
numeric, integer
factor

Body

The body of the template uses brew syntax with a forked back-end. Please check out pander’s documentation for details, in the followings the most important informations will be elaborated.

Brew syntaxes basically have two parts:

The special tags have two types:

These two codes look pretty the same and actually doesn’t differ too much, but still in a crucial way. Both of them are good for running R commands, but:

Let us show you some basic examples to show how they work and the difference between them!

Tags without equal sign:

<% if (2 > 1) { %> Math works, 2 is more than 1! <% } %> The following sentence will be written on the interface we use: “Math works, 2 is more than 1!”

Tags with the equal sign: <%= 2 > 1 %> That was not more complicated than just create a logical value with comparing two integer.

And obviously you can mix the two types as well:

<% if (2 > 1) { %> Math works? Is 2 really more than 1? Yeah, that's <%= 2 > 1 %>. <% } %> That will produce the same sentence like in the first example.

Here are a few useful calls, that you can use in the body section of a template:

If you need information about the variables from the dataset, you can use the followings (“var” is any input variable):

Translating templates

Translating an existing template could not be easier: just copy the content of the desired template to a new file and translate the text in the header and body of the template. Warning: this is harder than it seems!

See e.g. rapport:::rapport.find('i18n/hu/correlations') which is based on rapport:::rapport.find('correlations'). Check out the colorized diff of the two files!

Fields to be translated in header section (between <!--head and head--> tags):

In the body of the report (after head--> tag) you may change any text, reorder R code (stuff between <%= and %> tags) or even tweak those (if you know what you are doing).

We suggest placing the translated templates in a directory named to the short, alpha-2 abbreviation of the language (e.g. hu for Hungarian).

Translated (or just altered) templates are highly welcome, so please give the pull request a try or open an issue on GitHub.

Discussion

Please request a feature or file a bug report on issues page on GitHub. Feel free to watch and/or fork our project!

You can also start and/or join the discussion on various topics related to rapport (installation, configuration issues, questions, new templates, translation, etc.) via Google group.

License

This package is released under the Affero General Public License (ver. 3) based on FSF suggestions. Feel free to use our package and/or modify its source code in accordance with the licence conditions.

To cite package rapport in publications, please use:

Blagotić, A. and Daróczi, G. (2013). Rapport: a report templating
  system. R package version 0.51, URL
  http://cran.r-project.org/package=rapport

A BibTeX entry for LaTeX users is

  @Manual{,
    title = {Rapport: a report templating system},
    author = {Aleksandar Blagotić and Gergely Daróczi},
    year = {2013},
    note = {R package version 0.51},
    url = {http://cran.r-project.org/package=rapport},
  }

Thanks

Special thanks to:

and following authors for their immense effort in development of packages that rapport depends (or depended a while ago) on:

* the list is sorted alphabetically based on the package name

Contact

Gergely Daróczi

Ph.D. student at BCE, Hungary and co-founder of rapporter.net.

Aleksandar Blagotić

Psychology student at Faculty of Philosophy, Niš, Serbia and R/web-developer at rapporter.net.


© 2011-2013 rapport Development Team | License (AGPL3) | Styled with skeleton.