Manipulating and analyzing data with tidyverse
This lesson is derived from Data Carpentry teaching materials available under the CC BY 4.0 license:
https://datacarpentry.org/R-ecology-lesson/ https://datacarpentry.org/r-socialsci/
Objectives:
Describe the purpose of the
dplyr
andtidyr
packagesSelect columns in a data frame with the
dplyr
functionselect
Select rows in a data frame according to filter conditions with the
dplyr
functionfilter
Link the output of one
dplyr
function to the input of another function with the ‘pipe’ operator|>
Add new columns to a data frame that are functions of existing columns with
mutate
.Use the split-apply-combine concept for data analysis.
Use
summarize
,group_by
, andcount
to split a data frame into groups of observations, apply summary statistics for each group, and then combine the results.Describe the concept of a wide and a long table format and for which purpose those formats are useful.
Describe what key-value pairs are.
Reshape a data frame from long to wide format and back with the
pivot_wider
andpivot_longer
commands from thetidyr
packageImport a CSV file and export a data frame using the
read_csv
andwrite_csv
commands from thereadr
package
1. Data manipulation using dplyr
and
tidyr
Bracket subsetting is handy, but it can be cumbersome and difficult
to read, especially for complicated operations. Enter
dplyr
. dplyr
is a package for making tabular
data manipulation easier. It pairs nicely with tidyr
which
enables you to swiftly convert between different data formats for
plotting and analysis.
Packages in R are basically sets of additional functions that let you
do more stuff. The functions we’ve been using so far, like
str()
or data.frame()
, come built into R;
packages give you access to more of them. Before you use a package for
the first time you need to install it on your machine, and then you
should import it in every subsequent R session when you need it. The
RStudio session we are running already has the tidyverse
package installed. This is an “umbrella-package” that installs several
packages useful for data analysis which work together well such as
tidyr
, dplyr
, ggplot2
,
tibble
, etc.
The tidyverse
package tries to address 3 common issues
that arise when doing data analysis with some of the functions that come
with R:
- The results from a base R function sometimes depend on the type of data.
- Using R expressions in a non-standard way, which can be confusing for new learners.
- Hidden arguments, having default operations that new learners are not aware of.
We have seen in our previous lesson that when building or importing a
data frame, the columns that contain characters (i.e., text) are coerced
(=converted) into the factor
data type. We had to set
stringsAsFactors
to FALSE
to
avoid this hidden argument to convert our data type.
This time we will use the tidyverse
package to read the
data and avoid having to set stringsAsFactors
to
FALSE
.
Note: To install tidyverse
, one could
type install.packages("tidyverse")
straight into the
console. In fact, it would be better to write this in the console than
in our script for any package, as there’s no need to re-install packages
every time we run the script.
To load the package type:
## load the tidyverse packages, incl. dplyr
library(tidyverse)
2. What are dplyr
and tidyr
?
The package dplyr
provides easy tools for the most
common data manipulation tasks, and is built to work directly with data
frames.
Note: While we won’t be covering this topic further here, an additional feature is the ability to work directly with data stored in an external database. This addresses a common problem with R in that all operations are conducted in-memory and thus the amount of data you can work with is limited by available memory. The database connections essentially remove that limitation in that you can connect to a database of many hundreds of GB, conduct queries on it directly, and pull back into R only what you need for analysis.
The package tidyr
addresses the common problem of
wanting to reshape your data for plotting and use by different R
functions. Sometimes we want data sets where we have one row per
measurement. Sometimes we want a data frame where each measurement type
has its own column, and rows are instead more aggregated groups - like
plots or aquaria. Moving back and forth between these formats is
nontrivial, and tidyr
gives you tools for this and more
sophisticated data manipulation.
To learn more about dplyr
and tidyr
after
the workshop, you may want to check out this handy
data transformation with dplyr
cheatsheet and this one
about tidyr
.
We’ll read in our data using the read_csv()
function,
from the tidyverse package readr
, instead of
read.csv()
.
<- read_csv("/home/rstudio/shared/portal_data_joined.csv")
surveys
#> Rows: 34786 Columns: 13
#>
#> ── Column specification ─────────────────────────────────────────────────────────
#> Delimiter: ","
#> chr (6): species_id, sex, genus, species, taxa, plot_type
#> dbl (7): record_id, month, day, year, plot_id, hindfoot_length, weight
#>
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## inspect the data
str(surveys)
## preview the data
View(surveys)
The data are now in a format referred to as a “tibble”. Tibbles tweak some of the behaviors of the data frame objects we introduced previously. The data structure is very similar to a data frame. For our purposes the only differences are that:
- In addition to displaying the data type of each column under its name, it only prints the first few rows of data and only as many columns as fit on one screen.
- Columns of class
character
are never converted into factors.
We’re going to learn some of the most common dplyr
functions:
select()
: subset columnsfilter()
: subset rows on conditionsmutate()
: create new columns by using information from other columnssummarize()
: create summary statistics on (grouped) dataarrange()
: sort resultscount()
: count discrete values
3. Selecting columns and filtering rows
To select columns of a data frame, use select()
. The
first argument to this function is the data frame
(surveys
), and the subsequent arguments are the columns to
keep.
select(surveys, plot_id, species_id, weight)
To select all columns except certain ones, put a “-” in front of the variable to exclude it.
select(surveys, -record_id, -species_id)
This will select all variables in surveys
except
record_id
and species_id
.
To choose rows based on a specific criteria, use
filter()
:
filter(surveys, year == 1995)
4. Pipes
What if you want to select and filter at the same time? There are three ways to do this: use intermediate steps, nested functions or pipes.
With intermediate steps, you create a temporary data frame and use that as input to the next function, like this:
<- filter(surveys, weight < 5)
surveys2 <- select(surveys2, species_id, sex, weight) surveys_sml
This is readable, but can clutter up your workspace with lots of objects that you have to name individually. With multiple steps, that can be hard to keep track of.
You can also nest functions (i.e. one function inside of another), like this:
<- select(filter(surveys, weight < 5),
surveys_sml species_id, sex, weight)
This is handy, but can be difficult to read if too many functions are nested, as R evaluates the expression from the inside out (in this case, filtering, then selecting).
The last option, pipes, are a more recent addition
to R. Pipes let you take the output of one function and send it directly
to the next, which is useful when you need to do many things to the same
dataset. Pipes in R look like |>
(often called the
native pipe operator or base R pipe) or
%>%
(the magrittr pipe because it comes
from the magrittr
package, installed automatically with
dplyr
). For most purposes both pipes work the same way, but
it is better to pick one and use it consistently. In the course
materials, we will use the native pipe `|>´.
If you use RStudio, you can type the pipe with Ctrl
+
Shift
+ M
if you have a PC or Cmd
+ Shift
+ M
if you have a Mac. If this gives
you the magrittr pipe %>%
, you can change the shortcut
output to the native pipe |>
in the RStudio menu Tools
-> Global Options -> Code -> Use native pipe operator.
|>
surveys filter(weight < 5) |>
select(species_id, sex, weight)
In the above code, we use the pipe to send the surveys
dataset first through filter()
to keep rows where
weight
is less than 5, then through select()
to keep only the species_id
, sex
, and
weight
columns. Since |>
takes the object
on its left and passes it as the first argument to the function on its
right, we don’t need to explicitly include the data frame as an argument
to the filter()
and select()
functions any
more.
Some may find it helpful to read the pipe like the word “then”. For
instance, in the above example, we take the data frame
surveys
, then we filter
for rows with
weight < 5
, then we select
the
columns species_id
, sex
and
weight
. The dplyr
functions by themselves are
somewhat simple, but by combining them into linear workflows with the
pipe, we can accomplish more complex manipulations of data frames.
If we want to create a new object with this smaller version of the data, we can assign it a new name:
<- surveys |>
surveys_sml filter(weight < 5) |>
select(species_id, sex, weight)
surveys_sml
Note that the final data frame (surveys_sml
) is the
leftmost part of this expression.
Challenge
Go through the exercises in Data Manipulation Exercise Block 1 (~5 mins).
5. The mutate
function
Frequently you’ll want to create new columns based on the values in
existing columns, for example to do unit conversions, or to find the
ratio of values in two columns. For this we’ll use
mutate()
.
To create a new column of weight in kg:
|>
surveys mutate(weight_kg = weight / 1000)
You can also create a second new column based on the first new column
within the same call of mutate()
:
|>
surveys mutate(weight_kg = weight / 1000,
weight_kg2 = weight_kg * 2)
If this runs off your screen and you just want to see the first few
rows, you can use a pipe to view the head()
of the data.
(Pipes work with non-dplyr
functions, too).
|>
surveys mutate(weight_kg = weight / 1000) |>
head()
The first few rows of the output are full of NA
s, so if
we wanted to remove those we could insert a filter()
in the
chain:
|>
surveys filter(!is.na(weight)) |>
mutate(weight_kg = weight / 1000) |>
head()
is.na()
is a function that determines whether something
is an NA
. The !
symbol negates the result, so
we’re asking for every row where weight is not an
NA
.
Challenge
Go through Data Manipulation Exercise Block 2 (~5-10 mins).
6. Split-apply-combine and summarize
Many data analysis tasks can be approached using the
split-apply-combine paradigm: split the data into groups, apply
some analysis to each group, and then combine the results.
dplyr
makes this very easy through the function
summarize
and the argument .by
.
When groups are defined using the argument .by
, the
functionsummarize()
collapses each group into a single-row
summary of that group. .by
takes as arguments the column
names that contain the categorical variables for which
you want to calculate the summary statistics. So to compute the mean
weight
by sex:
|>
surveys summarize(mean_weight = mean(weight, na.rm = TRUE), .by = sex)
You may have noticed that the output from these calls doesn’t run off the screen anymore. It’s one of the advantages of the tibble format.
You can also group by multiple columns:
|>
surveys summarize(mean_weight = mean(weight, na.rm = TRUE),
.by = c(sex, species_id))
When grouping both by sex
and species_id
,
the last few rows are for animals that escaped before their sex and body
weights could be determined. We can use tail()
to look at
the last six rows in the data:
|>
surveys summarize(mean_weight = mean(weight, na.rm = TRUE),
.by = c(sex, species_id)) |>
tail()
You may notice that the last column does not contain NA
but NaN
(which refers to “Not a Number”). To avoid this, we
can remove the missing values for weight before we attempt to calculate
the summary statistics on weight. Because the missing values are removed
first, we can omit na.rm = TRUE
when computing the
mean:
|>
surveys filter(!is.na(weight)) |>
summarize(mean_weight = mean(weight),
.by = c(sex, species_id))
Here, again, the output from these calls doesn’t run off the screen
anymore. If you want to display more data, you can use the
print()
function at the end of your chain with the argument
n
specifying the number of rows to display:
|>
surveys filter(!is.na(weight)) |>
summarize(mean_weight = mean(weight), .by = c(sex, species_id)) |>
print(n = 15)
Challenge
There are a few other things we can try out using the split-apply-combine paradigm. Let’s try these out by going through the exercises in Data Manipulation Exercise Block 3 (10-15 mins).
7. Counting
When working with data, we often want to know the number of
observations found for each factor or combination of factors. For this
task, dplyr
provides count()
. For example, if
we wanted to count the number of rows of data for each sex, we would
do:
|>
surveys count(sex)
The count()
function is shorthand for something we’ve
already seen: grouping by a variable, and summarizing it by counting the
number of observations in that group. In other words,
surveys |> count()
is equivalent to:
|>
surveys summarise(count = n(), .by = sex)
For convenience, count()
provides the sort
argument:
|>
surveys count(sex, sort = TRUE)
Previous example shows the use of count()
to count the
number of rows/observations for one factor (i.e.,
sex
). If we wanted to count a combination of
factors, such as sex
and species
, we
would specify the first and the second factor as the arguments of
count()
:
|>
surveys count(sex, species)
With the above code, we can proceed with arrange()
to
sort the table according to a number of criteria so that we have a
better comparison. For instance, we might want to arrange the table
above in (i) an alphabetical order of the levels of the species and (ii)
in descending order of the count:
|>
surveys count(sex, species) |>
arrange(species, desc(n))
From the table above, we may learn that, for instance, there are 75
observations of the albigula species that are not specified for
its sex (i.e. NA
).
Challenge
Let’s have a look at the counting exercises in Data Manipulation Exercise Block 4 (~10 mins).
8. Reshaping with pivot_wider
and
pivot_longer
When we previously discussed recommended practices for data organisation, we were actually talking about how to structure our data according to the four rules defining a tidy dataset:
- Each variable has its own column
- Each observation has its own row
- Each value must have its own cell
- Each type of observational unit forms a table (rather than multiple tables)
In surveys
, the rows of surveys
contain
the values of variables associated with each record (the unit), values
such as the weight or sex of each animal associated with each record.
What if instead of comparing records, we wanted to compare the different
mean weight of each species between plots? (Ignoring
plot_type
for simplicity).
We’d need to create a new table where each row (the unit) is
comprised of values of variables associated with each plot. In practical
terms this means the values of the species in genus
would
become the names of column variables and the cells would contain the
values of the mean weight observed on each plot.
Having created a new table, it is straightforward to explore the relationship between the weight of different species within, and between, the plots. The key point here is that we are still following a tidy data structure, but we have reshaped the data according to the observations of interest: average species weight per plot instead of recordings per date.
The opposite transformation would be to transform column names into values of a variable.
We can do both these of transformations with two tidyr
functions, pivot_wider()
and pivot_longer()
.
These are relatively new functions that offer improvements over two
older functions that perform similar tasks: spread()
and
gather()
.
8a. From long to wide format using pivot_wider()
pivot_wider()
can be used to reshape a data set from
long format to wide format. To do this, we need to
provide (at least) the following arguments:
The data
The
names_from
variable, whose values will fill the new column variables.The
values_from
variable, whose values will fill the new column variables.
The following image illustrates the process for a randomly selected data set:
Further arguments include values_fill
which, if set,
fills in missing values with the value provided. More information on
arguments accepted by pivot_wider()
is provided on the function
website.
Let’s use pivot_wider()
to transform surveys to find the
mean weight of each species in each plot over the entire survey period.
First we use filter()
, group_by()
and
summarise()
to filter our observations and variables of
interest, and create a new variable for the mean_weight
. We
use the pipe as before too.
<- surveys |>
surveys_gw filter(!is.na(weight)) |>
summarize(mean_weight = mean(weight), .by = c(genus, plot_id))
str(surveys_gw)
This yields surveys_gw
where the observations for each
plot are spread across multiple rows, 196 observations of 3 variables.
Using pivot_wider()
with names from the column
genus
and values from mean_weight
, this
becomes 24 observations of 11 variables, one row for each plot. The
results can be organised by plot_id
using
arrange()
and we again use pipes:
<- surveys_gw |>
surveys_pivotwider pivot_wider(names_from = genus,
values_from = mean_weight) |>
arrange(plot_id)
surveys_pivotwider
8b. From wide to long format using pivot_longer()
The opposing situation could occur if we had been provided with data
in the form of surveys_pivotwider
(i.e. in wide format),
where the genus names are column names, but we wish to treat them as
values of a genus variable instead.
In this situation we want to take the column names and turn them into
a pair of new variables. One variable represents the column names as
values, and the other variable contains the values previously associated
with the column names. Instead of the names_from
and
values_from
arguments used by pivot_wider()
,
we use the arguments names_to
and
values_to
.
To recreate surveys_gw
from
surveys_pivotwider
, we need to assign names back to the
genus
column and values to a column called
mean_weight
, using all columns except plot_id
to retrieve the values. Here we drop the plot_id
column
with an exclamation mark sign. Note that, for the newly (re-)created
columns, we also need to provide quotation marks.
<- surveys_pivotwider |>
surveys_pivotlonger pivot_longer(!plot_id,
names_to = "genus",
values_to = "mean_weight") |>
arrange(genus)
surveys_pivotlonger
This will reshape a data set from wide to long
format. We could also have used a specification for what columns to
include. This can be useful if you have a large number of identifying
columns, and it’s easier to specify which columns to use than what to
leave alone. For that we would use the argument cols
:
Challenge
Have a look at Data Manipulation Exercise Block 5 (~15 mins).
9. write_csv
for data exporting
We previously used the write.csv
function call to export
our data from R. The package readr
(part of the
tidyverse
) comes with another function for exporting CSV
files: write_csv
. You might remember that when using
write.csv
, it was necessary to add an extra argument to
remove row numbers from the resulting CSV file
(row.names = FALSE
). The write_csv
function
never writes row names, which can simplify things when saving your data
for future use.
In preparation for our next lesson on plotting, we are going to prepare a cleaned up version of the data set that doesn’t include any missing data.
Let’s start by removing observations of animals for which
weight
and hindfoot_length
are missing, or the
sex
has not been determined:
<- surveys |>
surveys_complete filter(!is.na(weight), # remove missing weight
!is.na(hindfoot_length), # remove missing hindfoot_length
!is.na(sex)) # remove missing sex
Because we are interested in plotting how species abundances have changed through time, we are also going to remove observations for rare species (i.e., that have been observed less than 50 times). We will do this in two steps: first, we are going to create a data set that counts how often each species has been observed, and filter out the rare species. Second, we will extract only the observations for these more common species:
## Extract the most common species_id
<- surveys_complete |>
species_counts count(species_id) |>
filter(n >= 50)
## Only keep the most common species
<- surveys_complete |>
surveys_complete filter(species_id %in% species_counts$species_id)
To make sure that everyone has the same data set, check that
surveys_complete
has 30463 rows and 13 columns by typing
dim(surveys_complete)
.
Now that our data set is ready, we can save it as a CSV file in our
data_output
folder.
write_csv(surveys_complete, file = "data_output/surveys_complete.csv")
To make sure we’re all on the same page, these steps are replicated in Data Manipulation Exercise Block 6. Take some time (~5-10 mins) to run through them.