R Bootcamp - Day 7

tidyverse odds & ends

Author

Jay Hesselberth

Published

October 21, 2024

Class 7 outline

  • Accessing data in vectors (Exercise)
  • other tidyverse packages (stringr & forcats)
  • dplyr table joins (Exercise)
  • ggplot2 scale functions
  • ggplot2 multi-panel figures (Exercise)
  • ggplot2 saving figures

Accessing data in vectors

Using [, [[, and $

[ can return a range, [[ returns a single value.

vector selection with logic

one-step filtering.

two-step filtering. same result.

also can use with is.na() to identify / exclude NA values in a vector.

Use sum() to figure out how many are TRUE.

other tidyverse libraries

string operations with stringr

stringr provides several useful functions for operating on strings.

See the stringr cheatsheet

str_c() is similar to paste and paste0 but the behavior is more consistent.

forcats operations for factors

forcats provides several utilities for working with factors.

See the forcats cheatsheet

Use forcats to reorder aspects of plots

See the FAQ on rordering in ggplot2

dplyr

Combining tables by variables (i.e., columns)

  • bind_cols()
  • left_join()
  • right_join()
  • inner_join()
  • full_join()

Combining tables by cases (i.e., rows)

dplyr cheatsheet

Look at “combine variables” and “combine cases” at the top.

tables for joining

mutating joins - visualized

Joining tables by a variable - Exercise 1

filtering joins - visualized

Joining tables by a variable - Exercise 2

Other dplyr verbs

There are many other dplyr verbs.

  • We’ve used rename, count, add_row, add_column, distinct, sample_n, sample_frac, slice, pull

Check out the dplyr cheatsheet to learn more!

ggplot2

scale functions in ggplot2

  • scale_color_brewer() and scale_fill_brewer() control color and fill aesthetics.
  • See available ggplot2 brewer palettes

scale functions in ggplot2

Set up a points plot

How to combine multiple plots into a figure?

We have 4 legends - can they be condensed?

Yes, but it is not exactly straightforward.

Saving plots (Exercise 18)

Saves last plot as 5’ x 5’ file named plot_final.png in working directory.

Matches file type to file extension.