Introduction

Dplyr is one R package from the group of complementary packages which make up the tidyverse, and one of the tools I’ve found most useful over the past several years. For large data management projects, dplyr’s concise syntax makes it easy to debug, and it’s speed makes it practical to use on large data sets. It also supports databases.

Moreover, I’ve found it incredibly useful for data exploration.

Read and work through the following introduction to dplyr: PH-525x.

If you’d rather watch videos, there are many available on YouTube.

Next Steps

One topic which the tutorial above does not cover is the usefulness of ‘join’ operations in dplyr.

There are six principal joins:

Read the help page for these functions to understand what they’re for.

In practical usage, joining data is incredibly important for data management and analysis. Moreover, with dplyr, it can be done relatively concisely.

Example 1: Summarize and Join

This example computes summary statistics for a data set by group, and then joins the summary values back onto the original data set.

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
data(iris)
group_by(iris, Species) %>% summarize(avg_s_length = mean(Sepal.Length)) %>% right_join(iris, by = "Species")
## # A tibble: 150 x 6
##    Species avg_s_length Sepal.Length Sepal.Width Petal.Length Petal.Width
##     <fctr>        <dbl>        <dbl>       <dbl>        <dbl>       <dbl>
##  1  setosa        5.006          5.1         3.5          1.4         0.2
##  2  setosa        5.006          4.9         3.0          1.4         0.2
##  3  setosa        5.006          4.7         3.2          1.3         0.2
##  4  setosa        5.006          4.6         3.1          1.5         0.2
##  5  setosa        5.006          5.0         3.6          1.4         0.2
##  6  setosa        5.006          5.4         3.9          1.7         0.4
##  7  setosa        5.006          4.6         3.4          1.4         0.3
##  8  setosa        5.006          5.0         3.4          1.5         0.2
##  9  setosa        5.006          4.4         2.9          1.4         0.2
## 10  setosa        5.006          4.9         3.1          1.5         0.1
## # ... with 140 more rows

Example 2: Combine Data Sets

See example 2A from this lab.

Performance

One of the principal advantages of using packages such as dplyr, is that they are often optimized for performance. Consider the following example

N <- 1000000
ExampleData <- data.frame(gp = sample(c("A", "B", "C"), size = N, replace = TRUE), 
                          x1 = rnorm(N),
                          x2 = rnorm(N)^2)

system.time({group_info <- group_by(ExampleData, gp) %>% summarize(meanX1 = mean(x1), meanX2 = mean(x2))})
##    user  system elapsed 
##    0.06    0.00    0.06

This is both very concise, and very fast. If we want to perform the same operation using base R, there are a lot of options with potentially very different performance.

One method which might occur to you is to write a function which takes a single value of “gp”, subsets the data accordingly, and computes the summary statistics of interest. The resulting summaries could then be combined with “rbind”.

A concise version of this might look like the following:

system.time({group_info2 <- Reduce("rbind", lapply(unique(ExampleData$gp), function(g){
    dsub <- ExampleData[ExampleData$gp == g,]
    data.frame(group = g, meanX1 = mean(dsub$x1), meanX2 = mean(dsub$x2))
  }))})
##    user  system elapsed 
##    0.23    0.05    0.28

While this still runs pretty quickly, it’s quite a bit slower than the dplyr version. This would be even worse if there were a large number of groups, or this computation was nested inside a larger function.

Concluding Remarks

You may have noticed that some dplyr functions refer to columns of data frames without quotes. We’ll talk about this in more detail later, but it’s an example of Non-Standard-Evaluation. There are both benefits and drawbacks of non-standard evaluation in R, but it’s becoming popular in a number of packages, so it’s important to be aware of it.