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 moderately large data sets. It also supports databases, automatically translating dplyr code into SQL.
Moreover, I’ve found it incredibly useful for data exploration, since the syntax is easy to use with a sequential, exploratory approach. With these advantages in mind, however, it’s worth noting that dplyr can be slower in practice than alternatives, and it also has some headaches associated with using it in R packages. In addition, it can sometimes require more effort to write robust code - if something goes wrong (e.g., zero records are encountered where many were expected) mid-way through a large block of chained together dplyr code, cryptic errors often result.
To get an introduction, read and work through the following introduction to dplyr: PH-525x.
If you’d rather watch videos, there are many available on YouTube.
One topic which the tutorial above does not cover is the usefulness of ‘join’ operations in dplyr.
There are six principal joins:
These functions map generally onto the same operations found in SQL, and allow us to combine information from multiple data frames in useful ways. Read the help page for a quick runthrough of each join type:
library(dplyr)
help("right_join")
In practical usage, joining data is incredibly important for data management and analysis. Moreover, with dplyr, it can be done relatively concisely.
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
## <fct> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 setosa 5.01 5.1 3.5 1.4 0.2
## 2 setosa 5.01 4.9 3 1.4 0.2
## 3 setosa 5.01 4.7 3.2 1.3 0.2
## 4 setosa 5.01 4.6 3.1 1.5 0.2
## 5 setosa 5.01 5 3.6 1.4 0.2
## 6 setosa 5.01 5.4 3.9 1.7 0.4
## 7 setosa 5.01 4.6 3.4 1.4 0.3
## 8 setosa 5.01 5 3.4 1.5 0.2
## 9 setosa 5.01 4.4 2.9 1.4 0.2
## 10 setosa 5.01 4.9 3.1 1.5 0.1
## # ... with 140 more rows
See example 2A from this lab.
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.038 0.000 0.038
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.231 0.003 0.236
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.
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.
The data.table package provides an alternate syntax and set of tools for interacting with data. A good discussion of the performance and theoretical differences is given in this StackOverflow discussion.
Rather than focusing on verbs which are chained together to form larger conceptual operations on data sets, data.table
Explore the following vignette: Introduction to data.table.
Try playing around with the sample size below to see one example of the performance tradeoff:
library(data.table)
##
## Attaching package: 'data.table'
## The following objects are masked from 'package:dplyr':
##
## between, first, last
N <- 1000000
ExampleData.larger <- data.table(gp = sample(c("A", "B", "C"), size = N, replace = TRUE),
x1 = rnorm(N),
x2 = rnorm(N)^2)
ExampleData.largerdf <- as.data.frame(ExampleData.larger)
system.time({group_info <- group_by(ExampleData.largerdf, gp) %>% summarize(meanX1 = mean(x1), meanX2 = mean(x2))})
## user system elapsed
## 0.047 0.000 0.047
system.time({group_info2 <- ExampleData.larger[,.(meanX1 = mean(x1), meanX2 = mean(x2)), gp]})
## user system elapsed
## 0.033 0.003 0.033