R Tips and Tricks

Useful R snippets to remember

Data Manipulation

Mainly I'm trying to record tidyverse ways of doing things. Usually I know how to do them in base-R.

Selecting All Columns of a Given Type

This can be useful when you have lots of columns and want to just look at a certain type. Pipe it into `names()` to just get the names of the columns.

  data(swiss)
  swiss <- as_tibble(swiss)
  swiss %>% select(where(is.double))

A base-R version would be something like:

  data(swiss)
  swiss[, sapply(swiss, is.double)]

Graphics

Side-by-Side Histograms Before and After Log Transformation

Here's a quick and easy way to visually compare histograms of a variable before and after a log transformation. For easy repetition, you can string the last 4 lines together with `;` to create a one-liner, or better, turn them into a simple function. (I'm not sure of the relative strengths and weaknesses of the cowplot and patchwork packages, so I've included examples with both. See this stackoverflow question for other approaches.)

Using the cowplot package:

  library(cowplot)
  p <- ggplot(hcvvt, aes(x = my_variable))
  p1 <- p + geom_histogram()
  p2 <- p1 + scale_x_log10()
  plot_grid(p1, p2)

Using the patchwork package:

  library(patchwork)
  p <- ggplot(hcvvt, aes(x = my_variable))
  p1 <- p + geom_histogram()
  p2 <- p1 + scale_x_log10()
  p1 + p2
Brett Presnell
Brett Presnell
Associate Professor of Statistics

My research interests include nonparametric and computationally intensive statistics, model misspecification, statistical computing, and the analysis of directional data.