Data Wrangling  
with dplyr and tidyr  
Cheat Sheet 

Tidy Data  - A foundation for wrangling in R

F M A

F M A

In a tidy 
data set:

&

Each variable is saved 
in its own column

Each observation is 
saved in its own row

Tidy data complements R’s vectorized 
operations. R will automatically preserve 
observations as you manipulate variables. 
No other format works as intuitively with R.

*
AM

F

M * A

Syntax  - Helpful conventions for  wrangling

Reshaping Data  - Change the layout of a data set

dplyr::tbl_df(iris) 

Converts data to tbl class. tbl’s are easier to examine than 
data frames. R displays only the data that fits onscreen:

Source: local data frame [150 x 5] 

   Sepal.Length Sepal.Width Petal.Length 
1           5.1         3.5          1.4 
2           4.9         3.0          1.4 
3           4.7         3.2          1.3 
4           4.6         3.1          1.5 
5           5.0         3.6          1.4 
..          ...         ...          ... 
Variables not shown: Petal.Width (dbl), 
  Species (fctr)

dplyr::glimpse(iris) 

Information dense summary of tbl data. 

utils::View(iris) 

View data set in spreadsheet-like display (note capital V).

tidyr::gather(cases, "year", "n", 2:4) 

tidyr::spread(pollution, size, amount) 

Gather columns into rows.

Spread rows into columns.

wwwwwwA1005A1013A1010A1010
wwp1101101007
45451009

wwwwwwA1005A1013A1010A1010
wwp1101101007
45451009

wwp1101101007
45451009

tidyr::separate(storms, date, c("y", "m", "d")) 

tidyr::unite(data, col, ..., sep) 

Separate one column into several.

Unite several columns into one.

wwp1101101007
45451009

dplyr::data_frame(a = 1:3, b = 4:6) 
Combine vectors into data frame 
(optimized). 

dplyr::arrange(mtcars, mpg) 

Order rows by values of a column 
(low to high). 

dplyr::arrange(.mtcars, desc(mpg)) 
Order rows by values of a column 
(high to low). 

dplyr::rename(tb, y = year) 

Rename the columns of a data 
frame.

Subset Observations (Rows)

Subset Variables (Columns)

wwwww

110110110110110 wwww

dplyr::filter(iris, Sepal.Length > 7) 

dplyr::%>% 

Passes object on left hand side as first argument (or . 
argument) of function on righthand side. 

  x %>% f(y) is the same as   f(x, y) 
y %>% f(x, ., z) is the same as   f(x, y, z )

Extract rows that meet logical criteria. 

dplyr::distinct(iris) 

Remove duplicate rows. 

dplyr::sample_frac(iris, 0.5, replace = TRUE) 

Randomly select fraction of rows. 

dplyr::sample_n(iris, 10, replace = TRUE) 

Randomly select n rows. 

dplyr::slice(iris, 10:15) 

Select rows by position. 

dplyr::top_n(storms, 2, date) 

Select and order top n entries (by group if grouped data).

Logic in R  - ?Comparison, ?base::Logic

"Piping" with %>% makes code more readable, e.g. 

iris %>%  
  group_by(Species) %>% 
  summarise(avg = mean(Sepal.Width)) %>% 
  arrange(avg)

<

>

==

<=

>=

Less than

Greater than

Equal to

Less than or equal to

!=

%in%

is.na

!is.na

Not equal to

Group membership

Is NA

Is not NA

wppw11010071007110
451009100945

dplyr::select(iris, Sepal.Width, Petal.Length, Species) 

Select columns by name or helper function.

Helper functions for select - ?select

select(iris, contains(".")) 

Select columns whose name contains a character string. 

select(iris, ends_with("Length")) 

Select columns whose name ends with a character string. 

select(iris, everything()) 
Select every column. 

select(iris, matches(".t.")) 

Select columns whose name matches a regular expression. 

select(iris, num_range("x", 1:5)) 

Select columns named x1, x2, x3, x4, x5. 
select(iris, one_of(c("Species", "Genus"))) 

Select columns whose names are in a group of names. 

select(iris, starts_with("Sepal")) 

Select columns whose name starts with a character string. 

select(iris, Sepal.Length:Petal.Width) 

Select all columns between Sepal.Length and Petal.Width (inclusive). 

select(iris, -Species) 

RStudio® is a trademark of RStudio, Inc.  •  All rights reserved •  info@rstudio.com  •  844-448-1212 • rstudio.com 

devtools::install_github("rstudio/EDAWR") for data sets

Learn more with browseVignettes(package = c("dplyr", "tidyr"))  •  dplyr  0.4.0•  tidyr  0.2.0  •  Updated: 1/15

Greater than or equal to

&,|,!,xor,any,all

Boolean operators

Select all columns except Species. 

Summarise Data

Make New Variables

dplyr::summarise(iris, avg = mean(Sepal.Length)) 

Summarise data into single row of values. 
dplyr::summarise_each(iris, funs(mean)) 
Apply summary function to each column. 

dplyr::count(iris, Species, wt = Sepal.Length) 

Count number of rows with each unique value of 
variable (with or without weights).

dplyr::mutate(iris, sepal = Sepal.Length + Sepal. Width) 

Compute and append one or more new columns.  

dplyr::mutate_each(iris, funs(min_rank)) 
Apply window function to each column. 

dplyr::transmute(iris, sepal = Sepal.Length + Sepal. Width) 
Compute one or more new columns. Drop original columns.

summary 
function

window 
function

Summarise uses summary functions, functions that 
take a vector of values and return a single value, such as:

Mutate uses window functions, functions that take a vector of 
values and return another vector of values, such as:

dplyr::first 

min 

First value of a vector. 

Minimum value in a vector. 

dplyr::last 

max 

Last value of a vector. 

Maximum value in a vector. 

dplyr::nth 

mean 

Nth value of a vector. 

Mean value of a vector. 

dplyr::n 

median 

# of values in a vector. 

Median value of a vector. 

dplyr::n_distinct 

var 

# of distinct values in 
a vector. 

IQR 

IQR of a vector.

Variance of a vector. 

sd 

Standard deviation of a 
vector.

Group Data

dplyr::group_by(iris, Species) 

Group data into rows with the same value of Species. 

dplyr::ungroup(iris) 

dplyr::lead 

dplyr::cumall 

Copy with values shifted by 1. 

Cumulative all 

dplyr::lag 

Copy with values lagged by 1. 

dplyr::dense_rank 

Ranks with no gaps. 

dplyr::min_rank 

dplyr::cumany 

Cumulative any 
dplyr::cummean 

Cumulative mean 

cumsum 

Ranks. Ties get min rank. 

Cumulative sum 

dplyr::percent_rank 

cummax 

Ranks rescaled to [0, 1]. 

Cumulative max 

dplyr::row_number 

cummin 

Ranks. Ties got to first value. 

Cumulative min 

dplyr::ntile 

cumprod 

Bin vector into n buckets. 

Cumulative prod 

dplyr::between 

pmax 

Are values between a and b? 

Element-wise max 

dplyr::cume_dist 

pmin 

Combine Data Sets

a

x2
1
2
3

b

x1
A
B
D

x3
T
F
T

+

=

x1
A
B
C
Mutating Joins

x2
1
2
3

x3
T
F
NA

x2
x3
1
T
F
2
T NA

dplyr::left_join(a, b, by = "x1") 
Join matching rows from b to a.

dplyr::right_join(a, b, by = "x1") 
Join matching rows from a to b.

x1
A
B
C

x1
A
B
D

x1
A
B

x2
1
2

x2
x1
1
A
2
B
C
3
D NA

dplyr::inner_join(a, b, by = "x1") 

Join data. Retain only rows in both sets.

dplyr::outer_join(a, b, by = "x1") 

Join data. Retain all values, all rows.

x3
T
F

x3
T
F
NA
T

Filtering Joins

x1
A
B

x1
C

x2
1
2

x2
3

dplyr::semi_join(a, b, by = "x1") 

All rows in a that have a match in b.

dplyr::anti_join(a, b, by = "x1") 

All rows in a that do not have a match in b.

y

x2
1
2
3

z

x1
B
C
D

x2
2
3
4

+

=

x1
A
B
C
Set Operations

x1
B
C

x1
A
B
C
D

x1
A
D

x2
2
3

x2
1
2
3
4

x2
1
4

dplyr::intersect(y, z) 

Rows that appear in both y and z.

dplyr::union(y, z) 

Rows that appear in either or both y and z.

dplyr::setdiﬀ(y, z) 

Rows that appear in only one of y and z.

Remove grouping information from data frame. 

Cumulative distribution.

Element-wise min

Binding

iris   %>%   group_by(Species)   %>%   summarise(…) 

iris   %>%   group_by(Species)   %>%   mutate(…) 

Compute separate summary row for each group.

Compute new variables by group.

ir ir
C

x1
A
B
C
B
C
D

x1
B
C
D

x2
1
2
3
2
3
4

x2
2
3
4

x1
A
B
C

x2
1
2
3

dplyr::bind_rows(y, z) 

Append z to y as new rows.

dplyr::bind_cols(y, z) 

Append z to y as new columns.  
Caution: matches rows by position.

RStudio® is a trademark of RStudio, Inc.  •  All rights reserved •  info@rstudio.com  •  844-448-1212 • rstudio.com 

devtools::install_github("rstudio/EDAWR") for data sets

Learn more with browseVignettes(package = c("dplyr", "tidyr"))  •  dplyr  0.4.0•  tidyr  0.2.0  •  Updated: 1/15

