8 R Markdown in VSCode
R Markdown in VSCode, report generation in R, dynamic reports in R, VSCode for R Markdown, R Markdown tutorial
8.1 Introduction
R Markdown is a powerful tool for creating dynamic reports that combine code, narrative, and visualizations. In this chapter, we will explore how to set up and use R Markdown within VSCode for generating reproducible reports and documents.
8.2 Prerequisites
- Install essential tools for R programming in VSCode as outlined in the previous chapters (Chapter 2 and Chapter 3).
- Ensure you have the
rmarkdown
package installed in R and thevscode-R
extension in VSCode, as well as Pandoc for converting R Markdown documents to different output formats. Pandoc comes pre-installed with RStudio, but you can also install it separately from Pandoc’s official website.
8.3 Creating an R Markdown Document
To create a new R Markdown document in VSCode, follow these steps:
Create a New File: In VSCode, click on
File > New File
, then save it with the.Rmd
extension (e.g.,report.Rmd
).Add YAML Header: Start by adding a YAML header at the top of your file. This header defines the document’s title, author, output format, and other metadata.
--- title: "Data Analysis Report" author: "Your Name" date: "2024-12-06" output: html_document ---
Add Content: You can mix R code chunks, text, and visualizations in your R Markdown document. Use triple backticks with
{r}
to create a code chunk.## Introduction This is an example of an R Markdown document in VSCode. ```{r} summary(cars) ```
8.4 Running R Code in R Markdown
Place your cursor inside a code chunk and use the following shortcuts:
- Run Code Chunk: Press
Ctrl + Shift + Enter
(Windows/Linux) orCmd + Shift + Enter
(Mac) to execute the current chunk. - Run Line or Selection: Press
Ctrl + Enter
orCmd + Enter
to run the selected line or lines of code.
The output from the code will be displayed directly below the chunk, providing immediate feedback and results.
8.5 Generating Output
R Markdown allows you to generate documents in various formats, such as HTML, PDF, and Word. To knit
the document in VSCode:
- Open Command Palette: Press
F1
orCtrl + Shift + P
to open the command palette. - Run
Knit
Command: Typermarkdown: Render
and select the desired output format (e.g., HTML, PDF). - View the Output: The generated document will be saved in the same directory as your
.Rmd
file. You can view the HTML output directly in your browser or open a PDF/Word document.
8.6 Customizing R Markdown Output
VSCode allows you to customize the output of your R Markdown documents by editing the YAML header or adding custom parameters.
Themes and Highlighting: You can change the appearance of your document by specifying different themes and highlight styles in the YAML header.
output: html_document: theme: united highlight: tango
Parameterization: R Markdown documents can be parameterized, allowing you to create dynamic reports based on user inputs.
params: data_file: "data.csv"
You can then use
params$data_file
within your R code to reference the specified file.
8.7 Inline Code and Dynamic Text
R Markdown supports inline code to add dynamic content to your report. For example, you can include the current date or calculated values directly in the text:
`{r} Sys.Date()`, the dataset contains `{r} nrow(cars)` observations. As of
This feature is particularly useful for creating reproducible reports that update automatically when the data changes.
8.8 Best Practices for Report Generation
Organize Code into Chunks: Break your code into logical chunks and label each chunk for easy reference.
```{r load-data, echo=FALSE} data <- read.csv("data.csv") ```
Use Caching: For time-consuming computations, use the
cache = TRUE
option to avoid re-running the code every time youknit
the document.```{r model, cache=TRUE} model <- lm(mpg ~ wt + hp, data = mtcars) ```
Hide Code or Output: You can control the visibility of code and output by using chunk options like
echo
,results
, andinclude
.```{r, echo=FALSE} plot(mtcars$wt, mtcars$mpg) ```
8.9 Tips for Using R Markdown in VSCode
- Live Preview: Use the
Live Preview
extension to view changes in real-time as you edit your R Markdown document. - Code Folding: VSCode allows you to fold and unfold code chunks, making it easier to navigate large documents.
- Linting and Formatting: Use the
lintr
andstyler
packages for linting and formatting your R Markdown code to maintain readability and consistency.
8.10 Example of an R Markdown Document File Content
8.10.1 Source code
---
title: 'Example Report for R Markdown'
author: 'Datanovia'
date: '`{r} Sys.Date()`'
output: html_document
---
## Introduction
This R Markdown document provides a simple demonstration of using code, text, and visualizations together to create an interactive report.
## Summary of the `cars` Dataset
`cars` dataset in R contains speed and stopping distance data from the 1920s. Here is a summary of the data:
The
```{r}
summary(cars)
```
## Scatter Plot of Speed vs. Stopping Distance
Let's create a scatter plot to visualize the relationship between speed and stopping distance:
```{r}
plot(cars$speed, cars$dist,
xlab = "Speed (mph)",
ylab = "Stopping Distance (ft)",
main = "Speed vs. Stopping Distance")
```
## Conclusion
This is a simple example of how you can use R Markdown to create informative and visually appealing reports. You can mix text, R code, and visualizations to produce dynamic content.
Feel free to add more sections, analyses, or visualizations as you continue to explore the power of R Markdown!
8.10.2 Execution output
8.11 Conclusion
R Markdown in VSCode provides a flexible and efficient way to create dynamic, reproducible reports. You can generate professional-quality documents that integrate code, analysis and visualization.