R-markdown is a markdown file with embedded blocks of R code called chunks. There are two types of R code chunks: inline and block.
Inline chunks are added using the following syntax:
`r 2*2`
They are evaluated and inserted their output answer in place.
Block chunks have a different syntax:
```{r name, echo=TRUE, include=TRUE, ...}
2*2
````
And they come with several possible options. Here are the main ones (but there are many others):
They are written in a simple tag=value
format like in the example above.
Below is a basic example of R-markdown file illustrating the way R code chunks are embedded inside r-markdown.
# Title #
This is **plain markdown** text.
```{r code, include=FALSE, echo=FALSE}
# Just declare variables
income <- 1000
taxes <- 125
```
My income is: `r income ` dollars and I payed `r taxes ` dollars in taxes.
Below is the sum of money I will have left:
```{r gain, include=TRUE, echo=FALSE}
gain <- income-taxes
gain
```
```{r plotOutput, include=TRUE, echo=FALSE, fig.width=6, fig.height=6}
pie(c(income,taxes), label=c("income", "taxes"))
```
The R knitr
package can be used to evaluate R chunks inside R-markdown file and turn it into a regular markdown file.
The following steps are needed in order to turn R-markdown file into pdf/html:
knitr
.In addition to the above knitr
package has wrapper functions knit2html()
and knit2pdf()
that can be used to produce the final document without the intermediate step of manually converting it to the markdown format:
If the above example file was saved as income.Rmd
it can be converted to a pdf
file using the following R commands:
library(knitr)
knit2pdf("income.Rmd", "income.pdf")
The final document will be similar to the one below.