Embedding R-help with knitr
RStudio, R Markdown/knitr
and Git are great for teaching a statistics class.1 You can encourage good documentation (of both the development and the final result), an absolute necessity for reproducible research, via literate programming and DVCS. When using built in data sets for examples, it would be nice to include the description for their online help without resorting to copy and paste. Unfortunately, the naive approach
```{r}
?mtcars
```
does not work, because the online help works by side effect. Using help(...,help_type)
instead of ?
doesn’t help either.
StackOverflow as usual provides a place to get several useful answers. I’ve adapted / extended this answer to display the online help for a given data set inside a box.
<div style="border: 2px solid black; padding: 5px">
```{r, echo=FALSE, results='asis'}
tools:::Rd2HTML(utils:::.getHelpFile(help(mtcars)),stylesheet="")
```
</div>
This will also work for any thing accessible via the online help, but is less ideal for longer help pages because it placed completely inline. For longer help pages, you should probably add a maximum height and scrollbar to the outer div. Also, I’m not sure that the resulting document is 100% well-formed, because the quick-and-easy presented here doesn’t strip the <html>
, <head>
and <body>
tags from the document being embedded.
The output looks like this (note that CSS styles from the embedding document are carried over):
mtcars | R Documentation |
[, 1] | mpg | Miles/(US) gallon |
[, 2] | cyl | Number of cylinders |
[, 3] | disp | Displacement (cu.in.) |
[, 4] | hp | Gross horsepower |
[, 5] | drat | Rear axle ratio |
[, 6] | wt | Weight (lb/1000) |
[, 7] | qsec | 1/4 mile time |
[, 8] | vs | V/S |
[, 9] | am | Transmission (0 = automatic, 1 = manual) |
[,10] | gear | Number of forward gears |
[,11] | carb | Number of carburetors |
Source
Henderson and Velleman (1981), Building multiple regression models interactively. Biometrics, 37, 391–411.
Examples
require(graphics) pairs(mtcars, main = "mtcars data") coplot(mpg ~ disp | as.factor(cyl), data = mtcars, panel = panel.smooth, rows = 1)
-
Please note: your students will hate having to learn so much software and “computer science” at the start, but the not horrible ones will start to see the light the first time you correct a mistake and they can seamlessly pull in your changes or they delete their homework and can checkout the last version. ↩