Simple RMarkdown example with knitr

Jerzy Wieczorek, 2/10/2014

Intro to using RMarkdown

Click the MD toolbar button for help on Markdown.

Click Knit HTML button or press Ctrl+Shift+H to see your output.

Write your R code in “chunks”. The code, text output, and plot output will be shown:

# Make some data: y = x + e
x = 1:30
e = rnorm(30)
y = x + e
# Plot the data
plot(x, y, main = "y = x + e")
abline(lm(y ~ x))

plot of chunk unnamed-chunk-1

# Summarize the regression results
summary(lm(y ~ x))
## 
## Call:
## lm(formula = y ~ x)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -1.357 -0.715 -0.216  0.666  2.781 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -0.4657     0.3760   -1.24     0.23    
## x             1.0054     0.0212   47.47   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1 on 28 degrees of freedom
## Multiple R-squared:  0.988,  Adjusted R-squared:  0.987 
## F-statistic: 2.25e+03 on 1 and 28 DF,  p-value: <2e-16

More features of RMarkdown

Unlike in the R Notebok, we can change chunk options, e.g. figure size:

plot(x, y, main = "y = x + e")
abline(lm(y ~ x))

plot of chunk unnamed-chunk-2

We can use LaTeX equations: The data above came from the model \( y = x + \epsilon \) with \( \epsilon \sim N(0,1) \).

We can reference R results in the text output: The regression coefficient was 1.0054.

We can use the xtable package to print nice HTML tables:

library(xtable)
print(xtable(summary(lm(y ~ x))$coefficients, caption = "Regression results"), 
    type = "html")
Regression results
Estimate Std. Error t value Pr(> |t|)
(Intercept) -0.47 0.38 -1.24 0.23
x 1.01 0.02 47.47 0.00

Compare this to the default R output:

summary(lm(y ~ x))$coefficients
##             Estimate Std. Error t value  Pr(>|t|)
## (Intercept)  -0.4657    0.37600  -1.239 2.258e-01
## x             1.0054    0.02118  47.468 2.648e-28