R Markdown Tutorial
What is R Markdown?
R Markdown is a file format for making dynamic documents, reports, presentations, and dashboards with R. It combines R code with narrative text in a single document, allowing for reproducible research and the integration of code, output, and graphics.
Getting Started
To create an R Markdown document, you need to have R and RStudio installed. Here’s how to create a new R Markdown file:
1. Open RStudio.
2. Go to File > New File > R Markdown...
3. Fill in the Title, Author, and select the default output format (HTML, PDF, or Word).
4. Click OK.
Basic Structure of R Markdown
An R Markdown document has three main components:
- YAML Header: Contains metadata about the document.
- Markdown Text: The narrative text formatted using Markdown syntax.
- R Code Chunks: Blocks of R code that can be executed, and the results will be embedded in the document.
Here’s a simple example:
--- title: "My First R Markdown" author: "Your Name" date: "`r Sys.Date()`" output: html_document --- ## Introduction This is my first R Markdown document. ```{r} summary(cars) ``` ## Conclusion The summary of the cars dataset is shown above.
Rendering R Markdown
To render the R Markdown document and produce the output file, click the Knit button in RStudio. This will execute the R code chunks and generate the final document in the selected format.
The output will include both the text and the results of the R code chunks. For instance, if you knit the above example, you will see the summary statistics of the cars
dataset included in the output.
Using Code Chunks
Code chunks are enclosed by triple backticks and can be customized with various options. Here’s a breakdown of a code chunk:
```{r, echo=TRUE, eval=FALSE} # This is a code chunk plot(cars) ```
In this example:
- echo=TRUE: Show the code in the output document.
- eval=FALSE: Do not evaluate this code chunk.
Markdown Syntax
R Markdown supports standard Markdown syntax for formatting text. Here are some common elements:
- Headings: Use # for H1, ## for H2, ### for H3, etc.
- Bold: Use **text** or __text__.
- Italics: Use *text* or _text_.
- Lists: Use - for bullet points or numbers for ordered lists.
Conclusion
R Markdown is a powerful tool for creating dynamic and reproducible documents. By mixing code with narrative text, it allows researchers to share their findings in a clear and organized manner. Start using R Markdown today to enhance your reports and presentations!