R for the Rest of Us Cheatsheets

This is an in-progress version of cheatsheets for R in 3 Months participants and other people taking the R for the Rest of Us courses Fundamentals of R and Going Deeper with R.

General Syntax

Order Syntax Meaning Example
1 <- assignment operator x <- 10
2 -> alternative assignment 10 -> x
3 = assignment (mostly in function arguments) mean(x = c(1,2,3))
4 ! logical NOT operator: returns FALSE if statement is TRUE starwars |> filter(eye_color != “yellow”)
5 == equal x == y
6 > greater than x > y
7 < less than x < y
8 >= greater than or equal to x >= y
9 <= less than or equal to x <= y
10 | logical OR operator: returns TRUE if one of the statements is TRUE starwars |> filter(eye_color != “yellow” | height > 150)
11 & logical AND operator: returns TRUE if both elements are TRUE starwars |> filter(eye_color != “yellow” & height > 150)
12 : creates a sequence of numbers 1:10
13 %in% checks if a value is in a vector 3 %in% c(1,2,3,4)
14 ( ) used for function calls and precedence sum(1, 2, 3)
15 |> pipe operator mtcars |> select(mpg, cyl)
16 function() defines a function f <- function(x) x^2

Main packages used in our program

Copy the code below to install all the packages used in our program:

install.packages(c('dataReporter', 'dplyr', 'flextable', 'forcats', 'fs', 'ggplot2', 'ggrepel', 'ggtext', 
'ggthemes', 'glue', 'gtsummary', 'gt', 'janitor', 'marquee', 'pointblank', 'purrr', 'quarto', 'readr', 
'readxl', 'scales', 'skimr', 'stringr', 'tibble', 'tidyr'), 
dependencies = TRUE)

Main functions used in our program

Getting Started with R

[R in 3 Months] Week 1

In this week we learn how to import/read our data and packages, and explore it by creating quick summaries.

Order Function Name Package What it Does Example Category
1 install.packages() base R installs a package install.packages(“tidyverse”) Package Management
2 library() base R loads a package library(tidyverse) Package Management
3 read_csv() {readr} reads a csv file data <- read_csv(“data.csv”) Data Import/Export
4 glimpse() {dplyr} shows a summary of a data frame glimpse(penguins) Data Exploration
5 skim() {skimr} summary statistics about variables in data frames skim(penguins) Data Exploration
6 tbl_summary() {gtsummary} calculates descriptive statistics tbl_summary(penguins) Data Exploration
7 makeDataReport() {dataReporter} makes a data overview report makeDataReport(penguins) Data Exploration
8 scan_data() {pointblank} makes a data overview report scan_data(penguins) Data Exploration

Fundamentals of R

Data Wrangling and Analysis

[R in 3 Months] Week 2

These lessons teach us how to reduce our dataset to contain only variables and occurrences of interest, create new variables and summarise them.

Order Function Name Package What it Does Example Category
9 select() {dplyr} keep or drop columns starwars |> select(species, starships) Data Wrangling and Analysis
10 mutate() {dplyr} create, modify, and delete columns starwars |> mutate(body_ratio = mass / height) Data Wrangling and Analysis
11 filter() and filter_out() {dplyr} keep or drop rows that match a condition starwars |> filter(eye_color == “yellow”) Data Wrangling and Analysis
12 when_any() {dplyr} equivalent to x | y | z penguins |> filter(when_any(species == “Adelie”, species == “Chinstrap”)) Data Wrangling and Analysis
13 when_all() {dplyr} equivalent to x & y & z penguins |> filter(when_all(species %in% c(“Adelie”, “Chinstrap”), island == “Torgersen”)) Data Wrangling and Analysis
14 summarize() {dplyr} summarize a variable starwars |> summarize(avg_height = mean(height)) Data Wrangling and Analysis
15 view() {tibble} opens a data viewer in the IDE view(df) Data Exploration
16 group_by() {dplyr} group by one or more variables starwars |> group_by(species) |> summarize(avg_height = mean(height)) Data Wrangling and Analysis
17 max() and min() base R Returns the maxima and minima of the input values. df |> filter(value > min(value)) Data Wrangling and Analysis
18 arrange() {dplyr} order the rows of a data frame starwars |> arrange(desc(height)) Data Wrangling and Analysis
19 c() base R combines values into a vector c(1,2,3) Data Wrangling and Analysis
20 ends_with() {dplyr} select variables that ends with an exact suffix df |> select(ends_with(“name”)) Data Wrangling and Analysis

Data Visualization

[R in 3 Months] Week 3

In these lessons, we learned the basics of the grammar of graphics and how to make bar plots, scatterplots, and set some colours.

Order Function Name Package What it Does Example Category
21 ggplot() {ggplot2} initializes a ggplot object ggplot(data = starwars, aes(x = height, y = mass)) Data Visualization
22 aes() {ggplot2} defines aesthetic mappings aes(x = height, y = mass, color = gender) Data Visualization
23 coord_flip() {ggplot2} flips x and y axes ggplot(df) + coord_flip() Data Visualization
24 desc() {dplyr} sorts values in descending order arrange(desc(x)) Data Wrangling and Analysis
25 geom_point() {ggplot2} creates a scatterplot ggplot(starwars, aes(x = height, y = mass)) + geom_point() Data Visualization
26 geom_bar() {ggplot2} creates a bar chart ggplot(starwars, aes(x = species)) + geom_bar() Data Visualization
27 geom_histogram() {ggplot2} creates a histogram ggplot(starwars, aes(x = height)) + geom_histogram(binwidth = 10) Data Visualization
28 geom_label() {ggplot2} adds labeled text to plots geom_label(aes(label = x)) Data Visualization
29 geom_boxplot() {ggplot2} creates a boxplot ggplot(starwars, aes(x = gender, y = height)) + geom_boxplot() Data Visualization
30 geom_col() {ggplot2} creates a bar chart with precomputed values ggplot(df, aes(x, y)) + geom_col() Data Visualization
31 facet_wrap() {ggplot2} splits the plot into multiple panels ggplot(starwars, aes(x = height, y = mass)) + geom_point() + facet_wrap(vars(species)) Data Visualization
32 facet_grid() {ggplot2} creates a grid of plots ggplot(starwars, aes(x = height, y = mass)) + geom_point() + facet_grid(rows = vars(gender), cols = vars(species)) Data Visualization
33 labs() {ggplot2} adds labels to the plot ggplot(starwars, aes(x = height, y = mass)) + geom_point() + labs(title = “Height vs Mass in Star Wars”) Data Visualization
34 mean() base R calculates the average of values mean(x) Data Wrangling and Analysis
35 n() {dplyr} counts rows in a group summarize(n = n()) Data Wrangling and Analysis
36 number() {scales} low-level numeric formatter number(1234567, big.mark = “,”, decimal.mark = “.”, accuracy = 1) Data Visualization
37 read_tsv() {readr} reads a tab-separated file read_tsv(‘file.tsv’) Data Import/Export
38 theme() {ggplot2} customizes plot appearance ggplot(starwars, aes(x = height, y = mass)) + geom_point() + theme_minimal() Data Visualization
39 vars() {dplyr} tidy-select semantics for scoped verbs like mutate_at() and summarise_at(); superseded in favour of across() facet_wrap(vars(x)) Data Wrangling and Analysis
40 scale_color_manual() {ggplot2} manually sets color scale ggplot(starwars, aes(x = height, y = mass, color = gender)) + geom_point() + scale_color_manual(values = c(“blue”, “pink”, “purple”)) Data Visualization
41 scale_color_viridis_c() {ggplot2} applies continuous viridis color scale ggplot(df) + scale_color_viridis_c() Data Visualization
42 scale_color_viridis_d() {ggplot2} applies discrete viridis color scale ggplot(df) + scale_color_viridis_d() Data Visualization
43 scale_fill_manual() {ggplot2} manually sets fill colors ggplot(df) + scale_fill_manual(values = c(‘red’,‘blue’)) Data Visualization
44 scale_fill_viridis_c() {ggplot2} applies continuous viridis fill scale ggplot(df) + scale_fill_viridis_c() Data Visualization
45 scale_fill_viridis_d() {ggplot2} applies discrete viridis fill scale ggplot(df) + scale_fill_viridis_d() Data Visualization
46 theme_economist() {ggthemes} applies Economist-style theme to plots ggplot(df) + theme_economist() Data Visualization
47 theme_fivethirtyeight() {ggthemes} applies FiveThirtyEight-style theme ggplot(df) + theme_fivethirtyeight() Data Visualization
48 theme_light() {ggplot2} applies a light theme to plots ggplot(df) + theme_light() Data Visualization
49 ggsave() {ggplot2} saves plots to a file ggsave(filename = “plots/starwars-plot.pdf”, height = 8, width = 11, units = “in”) Data Visualization

Quarto

[R in 3 Months] Week 4

On week 4, we dive into Quarto and learn about code chunks, how to format text using Markdown, and how to render basic reports in PDF, Word and HTML.

Order Function Name Package What it Does Example Category
50 format: html Quarto sets document output format to HTML format: html Quarto
51 format: pdf Quarto sets document output format to PDF format: pdf Quarto
52 format: docx Quarto sets document output format to Word format: docx Quarto
53 toc: true Quarto adds a table of contents toc: true Quarto
54 Heading

Heading

Quarto creates a heading Heading

Heading

Quarto
55 bold Quarto formats text as bold **bold** Quarto
56 italic Quarto formats text as italic *italic* Quarto
57 Link Quarto creates a hyperlink [Google](https://www.google.com) Quarto
58 List item Quarto creates an unordered list - Item 1
- Item 2
- Item 3
Quarto
59 Ordered item
  1. Ordered item
Quarto creates an ordered list FirstSecondThird
  1. First
  2. Second
  3. Third
Quarto
60 Blockquote Quarto creates a blockquote > This is a blockquote Quarto
61 Inline code Quarto formats text as code The top response was `r top_response` Quarto
62 Code block Quarto creates a chunk of R code in a Quarto document ```{r}
library(tidyverse)
```
Quarto
63 Horizontal line Quarto creates a horizontal line --- Quarto
64 Image Quarto inserts an image ![Quarto Logo](quarto.png) Quarto
65 #| echo: false Quarto code chunk option to hide code but shows output echo: false Quarto
66 #| eval: false Quarto code chunk option to prevent code execution #| eval: false Quarto
67 #| warning: false Quarto code chunk option to hide warnings #| warning: false Quarto
68 #| message: false Quarto code chunk option to hide messages #| message: false Quarto
69 #| cache: Quarto code chunk option to cache code output #| cache: true Quarto
70 #| fig-align: ‘center’ Quarto code chunk option to align figure in the center #| fig-align: “center” Quarto
71 #| fig-cap: ‘Caption’ Quarto code chunk option to add a caption to a figure #| fig-cap: “Scatterplot” Quarto
72 #| fig-width: Quarto code chunk option to set figure width #| fig-width: 6 Quarto
73 #| fig-height: Quarto code chunk option to set figure height #| fig-height: 4 Quarto

Going Deeper with R

Advanced Data Wrangling

[R in 3 Months] Weeks 6, 7 and 8

In the advanced data wrangling section, we learn how to reshape our datasets and how to combine them. We also learn about the tidy principles and how to make a messy dataset more tidy.

Order Function Name Package What it Does Example Category
74 download.file() base R downloads a file from the Internet download.file(“url”, destfile = “my_path/my_file.csv”) Data Import/Export
75 read_excel() {readxl} reads an Excel file into R read_excel(“data.xlsx”, sheet = 1) Data Import/Export
76 recode_values() {dplyr} map old values to new values and creates a new vector recode_values(x, ‘A’ ~ ‘Alpha’, ‘B ~ ’Beta’) Data Wrangling and Analysis
77 recode() {dplyr} recodes values; superseeded in favor of recode_values() recode(x, A = ‘Alpha’) Data Wrangling and Analysis
78 replace_na() {tidyr} replaces NA values replace_na(x, 0) Data Wrangling and Analysis
79 write_csv() {readr} writes a dataframe to a CSV file write_csv(data, “output.csv”) Data Import/Export
80 pivot_longer() {tidyr} converts wide data into long format pivot_longer(data, cols = c(var1, var2), names_to = “variable”, values_to = “value”) Data Wrangling and Analysis
81 pivot_wider() {tidyr} converts long data into wide format pivot_wider(data, names_from = “variable”, values_from = “value”) Data Wrangling and Analysis
82 separate_wider_delim() {tidyr} separates one column into multiple columns separate_wider_delim(data, col = “variable”, into = c(“var1”, “var2”), sep = “_“) Data Wrangling and Analysis
83 set_names() {purrr} sets names for a vector set_names(x, c(‘a’,‘b’)) Data Wrangling and Analysis
84 separate_longer_delim() {tidyr} splits one column into multiple rows by a delimiter separate_longer_delim(data, col = “tags”, delim = “,”) Data Wrangling and Analysis
85 count() {dplyr} counts instances of unique values in a column data |> count(category) Data Wrangling and Analysis
86 distinct() {dplyr} returns unique rows in a dataset data |> distinct() Data Wrangling and Analysis
87 parse_number() {readr} extracts numbers from character strings parse_number(“$1,234.56”) Data Wrangling and Analysis
88 as.numeric() base R converts a column to numeric type as.numeric(c(“1”, “2”, “3”)) Data Wrangling and Analysis
89 case_when() {dplyr} performs conditional value assignment mutate(data, category = case_when(value > 10 ~ “High”, .default ~ “Low”)) Data Wrangling and Analysis
90 clean_names() {janitor} standardizes column names clean_names(df) Data Cleaning
91 case_match() {dplyr} maps values to new categories mutate(data, category = case_match(x, “A” ~ “Alpha”, “B” ~ “Beta”)) Data Wrangling and Analysis
92 na_if() {dplyr} replaces a specific value with NA mutate(data, var = na_if(var, “Unknown”)) Data Wrangling and Analysis
93 contains() {dplyr} selects columns that contain a string select(data, contains(“score”)) Data Wrangling and Analysis
94 starts_with() {dplyr} selects columns that start with a string select(data, starts_with(“age”)) Data Wrangling and Analysis
95 str_detect() {stringr} checks if a string contains a pattern filter(data, str_detect(name, “John”)) Data Wrangling and Analysis
96 str_remove() {stringr} removes pattern from strings str_remove(x, ‘a’) Data Wrangling and Analysis
97 str_replace() {stringr} replaces text patterns in a string mutate(data, name = str_replace(name, “Mr.”, ““)) Data Wrangling and Analysis
98 bind_rows() {dplyr} binds multiple dataframes by rows bind_rows(df1, df2) Data Wrangling and Analysis
99 inner_join() {dplyr} joins two datasets, keeping only matching rows inner_join(df1, df2, join_by(“id”)) Data Wrangling and Analysis
100 join_by() {dplyr} specifies join conditions left_join(df1, df2, join_by(id)) Data Wrangling and Analysis
101 left_join() {dplyr} joins two datasets, keeping all rows from the left left_join(df1, df2, join_by(“id”)) Data Wrangling and Analysis
102 right_join() {dplyr} joins two datasets, keeping all rows from the right right_join(df1, df2, join_by(“id”)) Data Wrangling and Analysis
103 full_join() {dplyr} joins two datasets, keeping all rows from both full_join(df1, df2, join_by(“id”)) Data Wrangling and Analysis
104 if_else() {dplyr} vectorized conditional function mutate(x = if_else(a > 0, ‘yes’,‘no’)) Data Wrangling and Analysis

Advanced Data Visualization

[R in 3 Months] Weeks 9, 10 and 11

This section teaches us how to make our plots look better. We learn how to tweak themes to declutter, highlight and explain.

Order Function Name Package What it Does Example Category
105 read_rds() {readr} reads an RDS file into R data <- read_rds(“data.rds”) Data Import/Export
106 write_rds() {readr} writes a data frame to an RDS file data |> write_rds(“data.rds”) Data Import/Export
107 ungroup() {dplyr} removes grouping structure from a dataset data |> ungroup() Data Wrangling and Analysis
108 is.nan() base R checks if a value is NaN (Not a Number) is.nan(c(1, NaN, 3)) Data Exploration
109 is.na() base R checks if a value is NA (Not Available) is.na(c(1, NA, 3)) Data Exploration
110 fct_reorder() {forcats} reorders a factor based on another variable data |> mutate(category = fct_reorder(category, value)) Data Wrangling and Analysis
111 geom_line() {ggplot2} adds a line plot layer to ggplot ggplot(data, aes(x, y)) + geom_line() Data Visualization
112 slice_max() {dplyr} selects rows with the highest values of a column data |> slice_max(order_by = value, n = 5) Data Wrangling and Analysis
113 pull() {dplyr} extracts a single column as a vector vector <- data |> pull(column_name) Data Wrangling and Analysis
114 fct_relevel() {forcats} relevels a factor, moving specified levels first data |>mutate(category = fct_relevel(category, “High”)) Data Wrangling and Analysis
115 lag() {dplyr} shifts values down by one or more rows data |> mutate(prev_value = lag(value)) Data Wrangling and Analysis
116 list() base R creates a list object list(a = 1, b = 2) Data Wrangling and Analysis
117 map() {purrr} applies a function to each element map(x, ~ .x * 2) Data Wrangling and Analysis
118 marquee_glue() {marquee} creates animated text labels marquee_glue(‘text’) Data Visualization
119 geom_text() {ggplot2} adds text labels to a ggplot ggplot(data, aes(x, y, label = label)) + geom_text() Data Visualization
120 geom_text_repel() {ggrepel} adds text labels that avoid overlapping ggplot(data, aes(x, y, label = label)) + geom_text_repel() Data Visualization
121 scale_y_continuous() {ggplot2} adjusts the y-axis scale ggplot(data, aes(x, y)) + scale_y_continuous(labels = scales::percent) Data Visualization
122 rename() {dplyr} renames columns in a dataset data |> rename(new_name = old_name) Data Wrangling and Analysis
123 reorder() {stats} reorders factor levels reorder(x, y) Data Wrangling and Analysis
124 scale_x_discrete() {ggplot2} customizes discrete x scale scale_x_discrete() Data Visualization
125 drop_na() {tidyr} removes rows with missing values drop_na(data, column_name) Data Wrangling and Analysis
126 element_blank() {ggplot2} removes plot elements theme(axis.text = element_blank()) Data Visualization
127 element_markdown() {ggtext} renders markdown in plot text element_markdown() Data Visualization
128 element_marquee() {marquee} adds animated text elements element_marquee() Data Visualization
129 element_text() {ggplot2} customizes text appearance element_text(size = 12) Data Visualization
130 everything() {dplyr} selects all columns select(everything()) Data Wrangling and Analysis
131 expansion() {ggplot2} controls axis expansion scale_x_continuous(expand = expansion()) Data Visualization
132 str_glue() {glue} creates formatted strings using variables data |> mutate(full_name = str_glue(“My name is {first_name} {last_name}”)) Data Wrangling and Analysis
133 sum() base R sums values sum(x) Data Wrangling and Analysis
134 theme_minimal() {ggplot2} applies minimal theme theme_minimal() Data Visualization
135 percent_format() {scales} formats numbers as percentages ggplot(data, aes(x, y)) + scale_y_continuous(labels = percent_format()) Data Visualization
136 percent() {scales} formats numbers as percentages percent(0.25) Data Visualization
137 annotate() {ggplot2} adds text or shapes to a ggplot ggplot(data, aes(x, y)) + annotate(“text”, x = 5, y = 10, label = “Note”) Data Visualization
138 as.character() base R converts to character as.character(x) Data Wrangling and Analysis
139 dir_create() {fs} creates directories dir_create(‘data/’) Data Import/Export

Advanced Quarto

[R in 3 Months] Week 12

In these option advanced Quarto lessons we learn how to make parameterized reports, how to use inline R code to print variables as text, and how to publish your reports.

Order Function Name Package What it Does Example Category
140 flextable() {flextable} creates a customizable table flextable(data) Tables
141 gt() {gt} creates a gt table for formatted output gt(data) Tables
142 cols_label() {gt} renames columns in a gt table data |> gt() |> cols_label(column_name = “New Label”) Tables
143 cols_width() {gt} sets column widths in a gt table data |> gt() |> cols_width(vars(column1) ~ px(100), vars(column2) ~ px(200)) Tables
144 cols_align() {gt} aligns columns in a gt table data |> gt() |> cols_align(align = “center”, columns = vars(column_name)) Tables
145 tab_caption() {gt} adds a caption below a gt table data |> gt() |> tab_caption(“This is a table caption.”) Tables
146 opt_interactive() {gt} makes the table interactive (sortable, searchable) data |> gt() |> opt_interactive() Tables
147 quarto_render() {quarto} renders a Quarto document to the specified format quarto_render(“report.qmd”, output_format = “html”) Quarto
148 tibble() {tibble} creates a modern data frame tibble(name = c(“Alice”, “Bob”), age = c(25, 30)) Quarto
149 pwalk() {purrr} iterates over multiple lists, applying a function pwalk(list(names, ages), ~ print(paste(.x, “is”, .y, “years old”))) Quarto