This is a minimal example of using knitr with in HTML pages. I am actually
using markdown here since it is more convenient in GitHub.
First, the input file was named as knitr-minimal.Rmd
(source),
and knitr will automatically determine the output filename to be
knitr-minimal.md (*.Rmd --> *.md).
# set global chunk options: images will be 5x5 inches
opts_chunk$set(fig.width = 5, fig.height = 5)
Now we write some code chunks in this markdown file:
## a simple calculator
(x <- 1 + 1)
## [1] 2
## boring random numbers
set.seed(123)
rnorm(5)
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929
We can also produce plots:
library(ggplot2)
qplot(hp, mpg, data = mtcars) + geom_smooth()
How to use xtable in Markdown!
library(xtable)
print(xtable(head(iris)), type = "html")
| Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species | |
|---|---|---|---|---|---|
| 1 | 5.10 | 3.50 | 1.40 | 0.20 | setosa |
| 2 | 4.90 | 3.00 | 1.40 | 0.20 | setosa |
| 3 | 4.70 | 3.20 | 1.30 | 0.20 | setosa |
| 4 | 4.60 | 3.10 | 1.50 | 0.20 | setosa |
| 5 | 5.00 | 3.60 | 1.40 | 0.20 | setosa |
| 6 | 5.40 | 3.90 | 1.70 | 0.40 | setosa |
Inline R code is also supported, e.g. the value of x is 2, and 2 times pi
= 6.2832.
This does not work
read_chunk("~/RStuff/knitrstitch.R")
Equation using \( \frac{1}{n} \sum_{i=i}^{n} x_{i} \)
So no more hesitation on using GitHub and knitr! You just write a minimal
amount of code to get beautiful output on the web.