Day 2: Manipulating Data
Overview
Teaching: min
Exercises: minQuestions
Objectives
Manipulating Data
Learning Objectives
Factors
- Describe what a factor is.
- Convert between strings and factors.
- Reorder and rename factors.
- Change how character strings are handled in a data frame.
Tidyverse
- Describe the purpose of the
dplyr
andtidyr
packages.- Select certain columns in a data frame with the
dplyr
functionselect
.- Select certain rows in a data frame according to filtering 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
spread
andgather
commands from thetidyr
package.- Export a data frame to a .csv file.
Fist we need to reload the surveys data frame.
surveys <- read.csv("data_raw/portal_data_joined.csv")
Factors
When we did str(surveys)
we saw that several of the columns consist of
integers.
Please note the default behavior of R has changed recently with the release of 4.0.0 [https://stat.ethz.ch/pipermail/r-announce/2020/000653.html].
If using R version 3.*.*: The columns genus
, species
, sex
,
plot_type
, … however, are of a special class called factor
.
If using R version 4.*.*: The columns genus
, species
, sex
,
plot_type
, … are strings! The behavior was changed so
stringsAsFactors = FALSE
is the default. So we are all working with
the same data types please reload the data using the following:
surveys <- read.csv("data_raw/portal_data_joined.csv", stringsAsFactors = TRUE)
Factors are very useful and actually contribute to making R particularly well suited to working with data. So we are going to spend a little time introducing them.
Factors represent categorical data. They are stored as integers associated with labels and they can be ordered or unordered. While factors look (and often behave) like character vectors, they are actually treated as integer vectors by R. So you need to be very careful when treating them as strings.
Once created, factors can only contain a pre-defined set of values, known as levels. By default, R always sorts levels in alphabetical order. For instance, if you have a factor with 2 levels:
sex <- factor(c("male", "female", "female", "male"))
R will assign 1
to the level "female"
and 2
to the level "male"
(because f
comes before m
, even though the first element in this
vector is "male"
). You can see this by using the function levels()
and you can find the number of levels using nlevels()
:
levels(sex)
nlevels(sex)
Sometimes, the order of the factors does not matter, other times you
might want to specify the order because it is meaningful (e.g., “low”,
“medium”, “high”), it improves your visualization, or it is required
by a particular type of analysis. Here, one way to reorder our levels in
the sex
vector would be:
sex # current order
> [1] male female female male
> Levels: female male
sex <- factor(sex, levels = c("male", "female"))
sex # after re-ordering
> [1] male female female male
> Levels: male female
In R’s memory, these factors are represented by integers (1, 2, 3), but
are more informative than integers because factors are self describing:
"female"
, "male"
is more descriptive than 1
, 2
. Which one is
“male”? You wouldn’t be able to tell just from the integer data.
Factors, on the other hand, have this information built in. It is
particularly helpful when there are many levels (like the species names
in our example dataset).
Converting factors
If you need to convert a factor to a character vector, you use
as.character(x)
.
as.character(sex)
In some cases, you may have to convert factors where the levels appear
as numbers (such as concentration levels or years) to a numeric vector.
For instance, in one part of your analysis the years might need to be
encoded as factors (e.g., comparing average weights across years) but in
another part of your analysis they may need to be stored as numeric
values (e.g., doing math operations on the years). This conversion from
factor to numeric is a little trickier. The as.numeric()
function
returns the index values of the factor, not its levels, so it will
result in an entirely new (and unwanted in this case) set of numbers.
One method to avoid this is to convert factors to characters, and then
to numbers.
Another method is to use the levels()
function. Compare:
year_fct <- factor(c(1990, 1983, 1977, 1998, 1990))
as.numeric(year_fct) # Wrong! And there is no warning...
as.numeric(as.character(year_fct)) # Works...
as.numeric(levels(year_fct))[year_fct] # The recommended way.
Notice that in the levels()
approach, three important steps occur:
- We obtain all the factor levels using
levels(year_fct)
- We convert these levels to numeric values using
as.numeric(levels(year_fct))
- We then access these numeric values using the underlying integers of
the vector
year_fct
inside the square brackets
Renaming factors
When your data is stored as a factor, you can use the plot()
function
to get a quick glance at the number of observations represented by each
factor level. Let’s look at the number of males and females captured
over the course of the experiment:
## bar plot of the number of females and males captured during the experiment:
plot(as.factor(surveys$sex))
In addition to males and females, there are about 1700 individuals for which the sex information hasn’t been recorded. Additionally, for these individuals, there is no label to indicate that the information is missing or undetermined. Let’s rename this label to something more meaningful. Before doing that, we’re going to pull out the data on sex and work with that data, so we’re not modifying the working copy of the data frame:
sex <- factor(surveys$sex)
head(sex)
> [1] M M
> Levels: F M
levels(sex)
> [1] "" "F" "M"
levels(sex)[1] <- "undetermined"
levels(sex)
> [1] "undetermined" "F" "M"
head(sex)
> [1] M M undetermined undetermined undetermined
> [6] undetermined
> Levels: undetermined F M
Challenge
- Rename “F” and “M” to “female” and “male” respectively.
- Now that we have renamed the factor level to “undetermined”, can you recreate the barplot such that “undetermined” is last (after “male”)?
Solution
levels(sex)[2:3] <- c(“female”, “male”) sex <- factor(sex, levels = c(“female”, “male”, “undetermined”)) plot(sex)
Stretch Challenge (Intermediate - 20 mins)
Group data from the continuous variable
hindfoot_length
into chunks of 10 units and convert this variable into a factor. i.e. you should have factor levels ‘0-10’, ‘11-20’, ‘21-30’, ‘31-40’, ‘41-50’, ‘51-60’, and ‘60+’.Create a barplot of
hindfoot_length
Solution
surveys(hindfoot_length[surveys)hindfoot_length <= 10] <- “0-10” surveys(hindfoot_length[surveys)hindfoot_length > 10 & surveys(hindfoot_length <= 20] <- “11-20” surveys)hindfoot_length[surveys(hindfoot_length > 20 & surveys)hindfoot_length <= 30] <- “21-30” surveys(hindfoot_length[surveys)hindfoot_length > 30 & surveys(hindfoot_length <= 40] <- “31-40” surveys)hindfoot_length[surveys(hindfoot_length > 40 & surveys)hindfoot_length <= 50] <- “41-50” surveys(hindfoot_length[surveys)hindfoot_length > 50 & surveys(hindfoot_length <= 60] <- “51-60” surveys)hindfoot_length[surveys$hindfoot_length > 60] <- “61+” surveys(hindfoot_length <- as.factor(surveys)hindfoot_length) plot(surveys$hindfoot_length)
Using stringsAsFactors=FALSE
In R versions previous to 4.0, when building or importing a data frame, the columns that contain characters (i.e. text) are coerced (= converted) into factors by default. However, since version 4.0 columns that contain characters (i.e. text) are NOT coerced (= converted) into factors.
Depending on what you want to do with the data, you may want to keep
these columns as character
or you may want them to be factor
.
read.csv()
and read.table()
have an argument called
stringsAsFactors
which can be set to FALSE
for character or TRUE
for factor.
In most cases, it is preferable to keep stringsAsFactors = FALSE
when
importing data and to convert as a factor only the columns that require
this data type.
## Compare the difference between our data read as `factor` vs `character`.
surveys <- read.csv("data_raw/portal_data_joined.csv", stringsAsFactors = TRUE)
str(surveys)
surveys <- read.csv("data_raw/portal_data_joined.csv", stringsAsFactors = FALSE)
str(surveys)
## Convert the column "plot_type" into a factor
surveys$plot_type <- factor(surveys$plot_type)
The automatic conversion of data type is sometimes a blessing, sometimes an annoyance. Be aware that it exists, learn the rules, and double check that data you import in R are of the correct type within your data frame.
Learning Objectives
Factors
Describe what a factor is.Convert between strings and factors.Reorder and rename factors.Change how character strings are handled in a data frame.Tidyverse
- Describe the purpose of the
dplyr
andtidyr
packages.- Select certain columns in a data frame with the
dplyr
functionselect
.- Select certain rows in a data frame according to filtering 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
spread
andgather
commands from thetidyr
package.- Export a data frame to a .csv file.
Data Manipulation using dplyr
and tidyr
Bracket subsetting is handy, but it can be cumbersome and difficult to
read, especially for complicated operations. 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. You should already have installed the
tidyverse
package. 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 above 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
If we haven’t already done so, we can type
install.packages("tidyverse")
straight into the console. In fact, it’s
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.
Then, to load the package type:
## load the tidyverse packages, incl. dplyr
library(tidyverse)
What are dplyr
and tidyr
?
The package dplyr
provides easy tools for the most common data
manipulation tasks, built to work directly with data frames.
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 (e.g., a time
period, an experimental unit like a plot or a batch number). Moving back
and forth between these formats is non-trivial, and tidyr
gives
you tools for this and more sophisticated data manipulation.
Note
An additional feature of
dplyr
is the ability to work directly with data stored in an external database. The benefits of doing this are that the data can be managed natively in a relational database, queries can be conducted on that database, and only the results of the query are returned. 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.
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
.
Stretch Challenge (Difficult - 30 mins)
Install and load dplyr and tidyr within your project environment. This is great for making your code reproducible. You can do this using renv
If you have more packages loaded, filter and select from dplyr can be overwritten by functions of the same name in different packages. Use
dplyr::select
or prioritize() to ensure you’re using the correct version of the function. {: .challenge}
Getting started with Tidyverse
We’ll read in our data using the read_csv()
function, from the
tidyverse package readr
, instead of read.csv()
.
surveys <- read_csv("data_raw/portal_data_joined.csv")
You will see the message Parsed with column specification
, followed by
each column name and its data type. When you execute read_csv
on a
data file, it looks through the first 1000 rows of each column and
guesses the data type for each column as it reads it into R. For
example, in this dataset, read_csv
reads weight
as col_double
(a
numeric data type), and species
as col_character
. You have the
option to specify the data type for a column manually by using the
col_types
argument in read_csv
.
## inspect the data
str(surveys)
## preview the data
View(surveys)
Notice that the class of the data is now tbl_df
This is referred to as a “tibble”. Tibbles tweak some of the behaviors of the data frame objects we introduced in the previous lesson. 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.
Managing Data with dplyr
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 columnsgroup_by()
andsummarize()
: create summary statistics on grouped dataarrange()
: sort resultscount()
: count discrete values
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 the variables in surveys
except record_id
and
species_id
.
To choose rows based on a specific criterion, use filter()
:
filter(surveys, year == 1995)
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:
surveys2 <- filter(surveys, weight < 5)
surveys_sml <- select(surveys2, species_id, sex, weight)
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:
surveys_sml <- select(filter(surveys, weight < 5), 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 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 %>%
and are made available via the magrittr
package,
installed automatically with dplyr
.
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 took the data frame surveys
, then
we filter
-ed for rows with weight < 5
, then we select
ed 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_sml <- surveys %>%
filter(weight < 5) %>%
select(species_id, sex, weight)
surveys_sml
Note that the final data frame is the leftmost part of this expression.
Challenge
Using pipes, subset the
surveys
data to include animals collected before 1995 and retain only the columnsyear
,sex
, andweight
.Solution
surveys %>% filter(year < 1995) %>% select(year, sex, weight)
Stretch Challenge (Intermediate - 15 mins)
Create
surveys_final
using as few lines of code as possible and using pipes to remove the intermediary variables.surveys_2 <- filter(surveys, year > 2000) surveys_3 <- filter(surveys_2, year != 2001) surveys_4 <- filter(surveys_3, plot_type == 'Control') surveys_5 <- select(surveys_4, record_id, month, day, year, sex, weight) surveys_final <- select(surveys_5, -day)
Solution
surveys_final <- surveys %>% filter(year < 1995, year != 2001, plot_type == ‘Control’) %>% select(record_id, month, year, sex, weight)
Mutate
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_lb = weight_kg * 2.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, as long as the dplyr
or
magrittr
package is loaded).
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
Create a new data frame from the
surveys
data that meets the following criteria: contains only thespecies_id
column and a new column calledhindfoot_cm
containing thehindfoot_length
values converted to centimeters. In thishindfoot_cm
column, there are noNA
s and all values are less than 3.Hint: think about how the commands should be ordered to produce this data frame!
Solution
surveys_hindfoot_cm <- surveys %>% filter(!is.na(hindfoot_length)) %>% mutate(hindfoot_cm = hindfoot_length / 10) %>% filter(hindfoot_cm < 3) %>% select(species_id, hindfoot_cm)
Stretch Challenge (Difficult - 20 mins)
- Create a new dataframe fom the
surveys
data with a new column calledweight_simplified
which has the value1
if weight is less than or equal to the mean weight and2
if the weight is more than the mean weight.Solution
surveys_simplified <- surveys %>% mutate(weight_simplified = ifelse(weight <= mean(weight, na.rm = TRUE), 1, 2))
- What’s the name of the function in
dplyr
which both selects and mutates? Have a look at the documentation for dplyrSolution
transmute
Split-apply-combine data analysis and the summarize()
function
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 use of the group_by()
function.
The summarize()
function
group_by()
is often used together with summarize()
, which collapses
each group into a single-row summary of that group. 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 %>%
group_by(sex) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE))
You may also have noticed that the output from these calls doesn’t run
off the screen anymore. It’s one of the advantages of tbl_df
over data
frame.
You can also group by multiple columns:
surveys %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE)) %>%
tail()
Here, we used tail()
to look at the last six rows of our summary.
Before, we had used head()
to look at the first six rows. We can see
that the sex
column contains NA
values because some animals had
escaped before their sex and body weights could be determined. The
resulting mean_weight
column does not contain NA
but NaN
(which
refers to “Not a Number”) because mean()
was called on a vector of
NA
values while at the same time setting na.rm = TRUE
. 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)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight))
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)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight)) %>%
print(n = 15)
Once the data are grouped, you can also summarize multiple variables at the same time (and not necessarily on the same variable). For instance, we could add a column indicating the minimum weight for each species for each sex:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight))
It is sometimes useful to rearrange the result of a query to inspect the
values. For instance, we can sort on min_weight
to put the lighter
species first:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight)) %>%
arrange(min_weight)
To sort in descending order, we need to add the desc()
function. If we
want to sort the results by decreasing order of mean weight:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight)) %>%
arrange(desc(mean_weight))
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 %>%
group_by(sex) %>%
summarize(count = n())
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
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
- How many animals were caught in each
plot_type
surveyed?Solution
surveys %>% count(plot_type)
A tibble: 5 × 2
plot_type n
1 Control 15611 2 Long-term Krat Exclosure 5118 3 Rodent Exclosure 4233 4 Short-term Krat Exclosure 5906 5 Spectab exclosure 3918
- Use
group_by()
andsummarize()
to find the mean, min, and max hindfoot length for each species (usingspecies_id
). Also add the number of observations (hint: see?n
).Solution
surveys %>% filter(!is.na(hindfoot_length)) %>% group_by(species_id) %>% summarize( mean_hindfoot_length = mean(hindfoot_length), min_hindfoot_length = min(hindfoot_length), max_hindfoot_length = max(hindfoot_length), n = n() )
A tibble: 25 × 5
species_id mean_hindfoot_length min_hindfoot_length max_hindfoot_length n
1 AH 33 31 35 2 2 BA 13 6 16 45 3 DM 36.0 16 50 9972 4 DO 35.6 26 64 2887 5 DS 49.9 39 58 2132 6 NL 32.3 21 70 1074 7 OL 20.5 12 39 920 8 OT 20.3 13 50 2139 9 OX 19.1 13 21 8 10 PB 26.1 2 47 2864 \# … with 15 more rows
- What was the heaviest animal measured in each year? Return the columns
year
,genus
,species_id
, andweight
.Solution
surveys %>% filter(!is.na(weight)) %>% group_by(year) %>% filter(weight == max(weight)) %>% select(year, genus, species, weight) %>% arrange(year)
A tibble: 27 × 4
Groups: year [26]
year genus species weight
1 1977 Dipodomys spectabilis 149 2 1978 Neotoma albigula 232 3 1978 Neotoma albigula 232 4 1979 Neotoma albigula 274 5 1980 Neotoma albigula 243 6 1981 Neotoma albigula 264 7 1982 Neotoma albigula 252 8 1983 Neotoma albigula 256 9 1984 Neotoma albigula 259 10 1985 Neotoma albigula 225 \# … with 17 more rows
Reshaping with pivot_wider and pivot_longer
In the spreadsheet lesson, we discussed how to structure our data leading 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
Here we examine the fourth rule: Each type of observational unit forms a table.
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 genus
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 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 therefore straightforward to explore the relationship between the weight of different genera 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 genus 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_longer()
and pivot_wider()
.
Pivot_wider
pivot_wider()
takes three principal arguments:
- the data
- names_from indicates which column (or columns) to get the name of the output column from
- values_from indicates which column (or columns) to get the cell values from
Further arguments include values_fill which, if set, fills in missing values with the value provided.
Let’s use pivot_wider()
to transform surveys to find the mean weight
of each genus in each plot over the entire survey period. We use
filter()
, group_by()
and summarize()
to filter our observations
and variables of interest, and create a new variable for the
mean_weight
.
surveys_gw <- surveys %>%
filter(!is.na(weight)) %>%
group_by(plot_id, genus) %>%
summarize(mean_weight = mean(weight))
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 genus
and values_from
mean_weight
this becomes 24 observations of 11 variables, one row for
each plot.
surveys_wide<- surveys_gw %>%
pivot_wider(names_from = genus, values_from = mean_weight)
str(surveys_wide)
We could now plot comparisons between the weight of genera in different plots, although we may wish to fill in the missing values first.
surveys_gw %>%
pivot_wider(names_from = genus, values_from = mean_weight, values_fill = 0) %>%
head()
Pivot_longer
The opposing situation could occur if we had been provided with data in
the form of surveys_wide
, where the genus names are column names, but
we wish to treat them as values of a genus variable instead.
In this situation we are gathering the column names and turning 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.
pivot_longer()
takes four principal arguments:
- the data
- cols indicates the columns to pivot into longer format (or those not to pivot)
- names_to indicates the name of the column to create from the data stored in the column names of data.
- values_to indicates the name of the column to create from the data stored in cell values.
To recreate surveys_gw
from surveys_wide
we would set names_to
genus
and values_to mean_weight
and use all columns except
plot_id
for the key variable. Here we exclude plot_id
from being
pivoted.
surveys_long <- surveys_wide %>%
pivot_longer(cols = -plot_id, names_to = "genus", values_to = "mean_weight")
str(surveys_long)
Note that now the NA
genera are included in the new pivot_longer
format. Using pivot_wider and then pivot_longer can be a useful way to
balance out a dataset so every replicate has the same composition.
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 what to pivot than what to leave alone. And
if the columns are directly adjacent, we don’t even need to list them
all out - just use the :
operator!
surveys_wide %>%
pivot_longer(cols = Baiomys:Spermophilus, names_to = "genus", values_to = "mean_weight") %>%
head()
Challenge
- Use
pivot_wider()
on thesurveys
data frame withyear
as columns,plot_id
as rows, and the number of genera per plot as the values. You will need to summarize before reshaping, and use the functionn_distinct()
to get the number of unique genera within a particular chunk of data. It’s a powerful function! See?n_distinct
for more.Solution
surveys_wide_genera <- surveys %>% group_by(plot_id, year) %>% summarize(n_genera = n_distinct(genus))%>% pivot_wider(names_from = year, values_from = n_genera)
head(surveys_wide_genera)
A tibble: 6 × 27
Groups: plot_id [6]
plot_id
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1 1 2 3 4 7 5 6 7 6 4 3 2 2 6 6 6 8 5 9 9 9 6 4 3 3 5 6 4 6 6 8 10 11 7 6 4 4 4 4 3 4 5 4 6 3 4 3 5 5 4 3 2 5 4 6 7 7 3 1 6 6 3 4 3 4 5 9 9 7 5 6 \# … with 16 more variables: 1987 , 1988 , 1989 , 1990 , \# 1991 , 1992 , 1993 , 1994 , 1995 , 1996 , \# 1997 , 1998 , 1999 , 2000 , 2001 , 2002
- Now take that data frame and
pivot_longer()
it again, so each row is a uniqueplot_id
byyear
combination.Solution
surveys_wide_genera %>% pivot_longer(cols = -plot_id, names_to = ‘year’, values_to = ‘n_genera’)
A tibble: 624 × 3
Groups: plot_id [24]
plot_id year n_genera
1 1 1977 2 2 1 1978 3 3 1 1979 4 4 1 1980 7 5 1 1981 5 6 1 1982 6 7 1 1983 7 8 1 1984 6 9 1 1985 4 10 1 1986 3 \# … with 614 more rows
- The
surveys
data set has two measurement columns:hindfoot_length
andweight
. This makes it difficult to do things like look at the relationship between mean values of each measurement per year in different plot types. Let’s walk through a common solution for this type of problem. First, usepivot_longer()
to create a dataset where we have a key column calledmeasurement
and avalue
column that takes on the value of eitherhindfoot_length
orweight
. Hint: You’ll need to specify which columns are being pivoted.Solution
surveys_long <- surveys %>% pivot_longer(cols = c(hindfoot_length, weight), names_to = “measurement”, values_to = “value”)
- With this new data set, calculate the average of each
measurement
in eachyear
for each differentplot_type
. Thenpivot_wider()
them into a data set with a column forhindfoot_length
andweight
. Hint: You only need to specify the name and value columns forpivot_wider()
.Solution
surveys_long %>% group_by(year, measurement, plot_type) %>% summarize(mean_value = mean(value, na.rm=TRUE)) %>% pivot_wider(names_from = measurement, values_from = mean_value)
A tibble: 130 × 4
Groups: year [26]
year plot_type hindfoot_length weight
1 1977 Control 36.1 50.4 2 1977 Long-term Krat Exclosure 33.7 34.8 3 1977 Rodent Exclosure 39.1 48.2 4 1977 Short-term Krat Exclosure 35.8 41.3 5 1977 Spectab exclosure 37.2 47.1 6 1978 Control 38.1 70.8 7 1978 Long-term Krat Exclosure 22.6 35.9 8 1978 Rodent Exclosure 37.8 67.3 9 1978 Short-term Krat Exclosure 36.9 63.8 10 1978 Spectab exclosure 42.3 80.1 \# … with 120 more rows
Exporting data
Now that you have learned how to use dplyr
to extract information
from or summarize your raw data, you may want to export these new data
sets to share them with your collaborators or for archival.
Similar to the read_csv()
function used for reading CSV files into R,
there is a write_csv()
function that generates CSV files from data
frames.
Before using write_csv()
, we are going to create a new folder, data
,
in our working directory that will store this generated dataset. We
don’t want to write generated datasets in the same directory as our
raw data. It’s good practice to keep them separate. The data_raw
folder should only contain the raw, unaltered data, and should be left
alone to make sure we don’t delete or modify it. In contrast, our script
will generate the contents of the data
directory, so even if the files
it contains are deleted, we can always re-generate them.
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_complete <- surveys %>%
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; then, we will extract only the observations for these more common species:
## Extract the most common species_id
species_counts <- surveys_complete %>%
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
folder.
write_csv(surveys_complete, file = "data/surveys_complete.csv")
Stretch Challenge (Fiendish - 45 mins)
Data can also be imported and exported in the form of binary files. Have a look at documentation for the readBin() and writeBin() functions, as well as this helpful guide to binary files in r. Then try to export the surveys data as a binary file before importing the binary file back into r.
Page built on: 📆 2022-07-19 ‒ 🕢 16:10:57
Key Points