Manipulating, analyzing and exporting data with tidyverse

Licenced under CC-BY 4.0 and OSI-approved licenses, see licensing.

Overview

Teaching: 40 min
Exercises: 15 min
Questions
  • How can I manipulate dataframes without repeating myself?

  • How do I save tabular data generated in R?

Objectives
  • Describe the purpose of the dplyr and tidyr packages.

  • Select certain columns in a data frame with the dplyr function select.

  • Extract certain rows in a data frame according to logical (boolean) conditions with the dplyr function filter.

  • Link the output of one dplyr function to the input of another function with the ‘pipe’ operator %>%.

  • Use the split-apply-combine concept for data analysis.

  • Use summarize, group_by, and count to split a data frame into groups of observations, apply summary statistics for each group, and then combine the results.

  • 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.

The tidyverse package is an “umbrella-package” that installs tidyr, dplyr, and several other packages useful for data analysis, such as 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:

  1. The results from a base R function sometimes depend on the type of data.
  2. Using R expressions in a non standard way, which can be confusing for new learners.
  3. Hidden arguments, having default operations that new learners are not aware of.

You should already have installed and loaded the tidyverse package. If we haven’t already done so, we can type install.packages("tidyverse") straight into the console. Then, to load the package type library(tidyverse).

What are dplyr and tidyr?

The package dplyr provides easy tools for the most common data manipulation tasks. It is built to work directly with data frames, with many common tasks optimized by being written in a compiled language (C++). An additional feature 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 this 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 (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.

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.

As before, we’ll read in our data using the read_csv() function from the tidyverse package readr.

download.file(
  url = "https://nbisweden.github.io/module-r-intro-dm-practices/data/Hawks.csv",
  destfile = "data_raw/Hawks.csv"
)
## load the tidyverse packages, incl. dplyr
library(tidyverse)

We can then read the data into memory:

hawks <- read_csv("data_raw/Hawks.csv")
Rows: 908 Columns: 19
── Column specification ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Delimiter: ","
chr   (5): CaptureTime, BandNumber, Species, Age, Sex
dbl  (13): Month, Day, Year, Wing, Weight, Culmen, Hallux, Tail, StandardTai...
time  (1): ReleaseTime

ℹ 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(hawks)
spec_tbl_df [908 × 19] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ Month       : num [1:908] 9 9 9 9 9 9 9 9 9 9 ...
 $ Day         : num [1:908] 19 22 23 23 27 28 28 29 29 30 ...
 $ Year        : num [1:908] 1992 1992 1992 1992 1992 ...
 $ CaptureTime : chr [1:908] "13:30" "10:30" "12:45" "10:50" ...
 $ ReleaseTime : 'hms' num [1:908] NA NA NA NA ...
  ..- attr(*, "units")= chr "secs"
 $ BandNumber  : chr [1:908] "877-76317" "877-76318" "877-76319" "745-49508" ...
 $ Species     : chr [1:908] "RT" "RT" "RT" "CH" ...
 $ Age         : chr [1:908] "I" "I" "I" "I" ...
 $ Sex         : chr [1:908] NA NA NA "F" ...
 $ Wing        : num [1:908] 385 376 381 265 205 412 370 375 412 405 ...
 $ Weight      : num [1:908] 920 930 990 470 170 1090 960 855 1210 1120 ...
 $ Culmen      : num [1:908] 25.7 NA 26.7 18.7 12.5 28.5 25.3 27.2 29.3 26 ...
 $ Hallux      : num [1:908] 30.1 NA 31.3 23.5 14.3 32.2 30.1 30 31.3 30.2 ...
 $ Tail        : num [1:908] 219 221 235 220 157 230 212 243 210 238 ...
 $ StandardTail: num [1:908] NA NA NA NA NA NA NA NA NA NA ...
 $ Tarsus      : num [1:908] NA NA NA NA NA NA NA NA NA NA ...
 $ WingPitFat  : num [1:908] NA NA NA NA NA NA NA NA NA NA ...
 $ KeelFat     : num [1:908] NA NA NA NA NA NA NA NA NA NA ...
 $ Crop        : num [1:908] NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, "spec")=
  .. cols(
  ..   Month = col_double(),
  ..   Day = col_double(),
  ..   Year = col_double(),
  ..   CaptureTime = col_character(),
  ..   ReleaseTime = col_time(format = ""),
  ..   BandNumber = col_character(),
  ..   Species = col_character(),
  ..   Age = col_character(),
  ..   Sex = col_character(),
  ..   Wing = col_double(),
  ..   Weight = col_double(),
  ..   Culmen = col_double(),
  ..   Hallux = col_double(),
  ..   Tail = col_double(),
  ..   StandardTail = col_double(),
  ..   Tarsus = col_double(),
  ..   WingPitFat = col_double(),
  ..   KeelFat = col_double(),
  ..   Crop = col_double()
  .. )
 - attr(*, "problems")=<externalptr> 
## preview the data
view(hawks)

Next, we’re going to learn some of the most common dplyr functions:

  • select(): subset columns
  • filter(): subset rows on conditions
  • mutate(): create new columns by using information from other columns
  • group_by() and summarize(): create summary statistics on grouped data
  • arrange(): sort results
  • count(): 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 (hawks), and the subsequent arguments are the columns to keep.

select(hawks, Species, Sex, Weight)

To select all columns except certain ones, put a “-“ in front of the variable to exclude it.

select(hawks, -BandNumber, -Culmen)

This will select all the variables in hawks except BandNumber and Culmen.

To choose rows based on a specific criterion, use filter():

filter(hawks, Sex == "F")
# A tibble: 174 × 19
   Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex  
   <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr>
 1     9    23  1992 10:50          NA       745-49508  CH      I     F    
 2     9    27  1992 11:15          NA       1253-98801 SS      I     F    
 3    10    27  1992 10:05          NA       1253-98802 SS      I     F    
 4     9    29  1993 10:25          NA       1253-98803 SS      I     F    
 5    10     1  1993 10:20          NA       745-49512  CH      I     F    
 6    10    12  1993 13:15          NA       745-49515  CH      I     F    
 7    10    14  1993 14:05          NA       1373-35272 SS      A     F    
 8     9     8  1994 12:10          NA       1423-16201 SS      I     F    
 9     9     9  1994 9:02           NA       2003-58433 SS      I     F    
10     9    20  1994 9:05           NA       2003-58435 SS      A     F    
# … with 164 more rows, and 10 more variables: Wing <dbl>, Weight <dbl>,
#   Culmen <dbl>, Hallux <dbl>, Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>,
#   WingPitFat <dbl>, KeelFat <dbl>, Crop <dbl>

We can also filter rows that do not contain missing data in some columns:

filter(hawks, !is.na(Sex) & !is.na(Weight))
# A tibble: 327 × 19
   Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex  
   <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr>
 1     9    23  1992 10:50          NA       745-49508  CH      I     F    
 2     9    27  1992 11:15          NA       1253-98801 SS      I     F    
 3    10    23  1992 16:05          NA       1173-19901 SS      I     M    
 4    10    27  1992 10:05          NA       1253-98802 SS      I     F    
 5     9    13  1993 14:25          NA       173-19904  SS      I     M    
 6     9    17  1993 15:25          NA       193-19905  SS      I     M    
 7     9    29  1993 10:25          NA       1253-98803 SS      I     F    
 8    10     1  1993 10:20          NA       745-49512  CH      I     F    
 9    10     1  1993 10:45          NA       745-49513  CH      A     M    
10    10    11  1993 11:35          NA       1173-19906 SS      I     M    
# … with 317 more rows, and 10 more variables: Wing <dbl>, Weight <dbl>,
#   Culmen <dbl>, Hallux <dbl>, Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>,
#   WingPitFat <dbl>, KeelFat <dbl>, Crop <dbl>

This will return all rows that have a value in both the Sex column and the Weight column. In Tidyverse, there is also a special functions drop_na that can be used to filter out rows with missing data:

drop_na(hawks, Sex, Weight)
# A tibble: 327 × 19
   Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex  
   <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr>
 1     9    23  1992 10:50          NA       745-49508  CH      I     F    
 2     9    27  1992 11:15          NA       1253-98801 SS      I     F    
 3    10    23  1992 16:05          NA       1173-19901 SS      I     M    
 4    10    27  1992 10:05          NA       1253-98802 SS      I     F    
 5     9    13  1993 14:25          NA       173-19904  SS      I     M    
 6     9    17  1993 15:25          NA       193-19905  SS      I     M    
 7     9    29  1993 10:25          NA       1253-98803 SS      I     F    
 8    10     1  1993 10:20          NA       745-49512  CH      I     F    
 9    10     1  1993 10:45          NA       745-49513  CH      A     M    
10    10    11  1993 11:35          NA       1173-19906 SS      I     M    
# … with 317 more rows, and 10 more variables: Wing <dbl>, Weight <dbl>,
#   Culmen <dbl>, Hallux <dbl>, Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>,
#   WingPitFat <dbl>, KeelFat <dbl>, Crop <dbl>

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:

hawks_female <- filter(hawks, Sex == "F")
hawks_female_sml <- select(hawks_female, Species, 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:

hawks_female <- select(
  filter(hawks, Sex == "F"), Species, 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. 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.

hawks %>%
  filter(Sex == "F") %>%
  select(Species, Sex, Weight)
# A tibble: 174 × 3
   Species Sex   Weight
   <chr>   <chr>  <dbl>
 1 CH      F        470
 2 SS      F        170
 3 SS      F        180
 4 SS      F        134
 5 CH      F        340
 6 CH      F        475
 7 SS      F         NA
 8 SS      F        194
 9 SS      F        159
10 SS      F        168
# … with 164 more rows

In the above code, we use the pipe to send the hawks dataset first through filter() to keep rows where Sex equals "F", then through select() to keep only the Species, 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 hawks, then we filtered for rows with Sex == "F", then we selected columns Species, 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:

hawks_female <- hawks %>%
  filter(Sex == "F") %>%
  select(Species, Sex, Weight)

hawks_female
# A tibble: 174 × 3
   Species Sex   Weight
   <chr>   <chr>  <dbl>
 1 CH      F        470
 2 SS      F        170
 3 SS      F        180
 4 SS      F        134
 5 CH      F        340
 6 CH      F        475
 7 SS      F         NA
 8 SS      F        194
 9 SS      F        159
10 SS      F        168
# … with 164 more rows

Note that the final data frame is the leftmost part of this expression.

Challenge 3.1

Using pipes, subset the hawks data to include only males with a weight (column Weight) greater than 500 g, and retain only the columns Species and Weight.

Solution

hawks %>%
 filter(Sex == "M" & Weight > 500) %>%
 select(Species, Weight)
# A tibble: 5 × 2
  Species Weight
  <chr>    <dbl>
1 CH         550
2 SS         550
3 CH         742
4 SS        1094
5 RT        1080

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:

hawks %>%
  mutate(Weight_kg = Weight / 1000)
# A tibble: 908 × 20
   Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex  
   <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr>
 1     9    19  1992 13:30          NA       877-76317  RT      I     <NA> 
 2     9    22  1992 10:30          NA       877-76318  RT      I     <NA> 
 3     9    23  1992 12:45          NA       877-76319  RT      I     <NA> 
 4     9    23  1992 10:50          NA       745-49508  CH      I     F    
 5     9    27  1992 11:15          NA       1253-98801 SS      I     F    
 6     9    28  1992 11:25          NA       1207-55910 RT      I     <NA> 
 7     9    28  1992 13:30          NA       877-76320  RT      I     <NA> 
 8     9    29  1992 11:45          NA       877-76321  RT      A     <NA> 
 9     9    29  1992 15:35          NA       877-76322  RT      A     <NA> 
10     9    30  1992 13:45          NA       1207-55911 RT      I     <NA> 
# … with 898 more rows, and 11 more variables: Wing <dbl>, Weight <dbl>,
#   Culmen <dbl>, Hallux <dbl>, Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>,
#   WingPitFat <dbl>, KeelFat <dbl>, Crop <dbl>, Weight_kg <dbl>

You can also create a second new column based on the first new column within the same call of mutate():

hawks %>%
  mutate(Weight_kg = Weight / 1000,
         Weight_lb = Weight_kg * 2.2)
# A tibble: 908 × 21
   Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex  
   <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr>
 1     9    19  1992 13:30          NA       877-76317  RT      I     <NA> 
 2     9    22  1992 10:30          NA       877-76318  RT      I     <NA> 
 3     9    23  1992 12:45          NA       877-76319  RT      I     <NA> 
 4     9    23  1992 10:50          NA       745-49508  CH      I     F    
 5     9    27  1992 11:15          NA       1253-98801 SS      I     F    
 6     9    28  1992 11:25          NA       1207-55910 RT      I     <NA> 
 7     9    28  1992 13:30          NA       877-76320  RT      I     <NA> 
 8     9    29  1992 11:45          NA       877-76321  RT      A     <NA> 
 9     9    29  1992 15:35          NA       877-76322  RT      A     <NA> 
10     9    30  1992 13:45          NA       1207-55911 RT      I     <NA> 
# … with 898 more rows, and 12 more variables: Wing <dbl>, Weight <dbl>,
#   Culmen <dbl>, Hallux <dbl>, Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>,
#   WingPitFat <dbl>, KeelFat <dbl>, Crop <dbl>, Weight_kg <dbl>,
#   Weight_lb <dbl>

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).

hawks %>%
  mutate(Weight_kg = Weight / 1000) %>%
  head()
# A tibble: 6 × 20
  Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex    Wing
  <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr> <dbl>
1     9    19  1992 13:30          NA       877-76317  RT      I     <NA>    385
2     9    22  1992 10:30          NA       877-76318  RT      I     <NA>    376
3     9    23  1992 12:45          NA       877-76319  RT      I     <NA>    381
4     9    23  1992 10:50          NA       745-49508  CH      I     F       265
5     9    27  1992 11:15          NA       1253-98801 SS      I     F       205
6     9    28  1992 11:25          NA       1207-55910 RT      I     <NA>    412
# … with 10 more variables: Weight <dbl>, Culmen <dbl>, Hallux <dbl>,
#   Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>, WingPitFat <dbl>,
#   KeelFat <dbl>, Crop <dbl>, Weight_kg <dbl>

The first few rows of the output are full of NAs, so if we wanted to remove those we could insert a filter() in the chain:

hawks %>%
  filter(!is.na(Weight)) %>%
  mutate(Weight_kg = Weight / 1000) %>%
  head()
# A tibble: 6 × 20
  Month   Day  Year CaptureTime ReleaseTime BandNumber Species Age   Sex    Wing
  <dbl> <dbl> <dbl> <chr>       <time>      <chr>      <chr>   <chr> <chr> <dbl>
1     9    19  1992 13:30          NA       877-76317  RT      I     <NA>    385
2     9    22  1992 10:30          NA       877-76318  RT      I     <NA>    376
3     9    23  1992 12:45          NA       877-76319  RT      I     <NA>    381
4     9    23  1992 10:50          NA       745-49508  CH      I     F       265
5     9    27  1992 11:15          NA       1253-98801 SS      I     F       205
6     9    28  1992 11:25          NA       1207-55910 RT      I     <NA>    412
# … with 10 more variables: Weight <dbl>, Culmen <dbl>, Hallux <dbl>,
#   Tail <dbl>, StandardTail <dbl>, Tarsus <dbl>, WingPitFat <dbl>,
#   KeelFat <dbl>, Crop <dbl>, Weight_kg <dbl>

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 3.2

Create a new data frame from the hawks data that meets the following criteria: contains only the Species column and a new column called Tarsus_cm containing the Tarsus values (currently in mm) converted to centimeters. Furthermore, include only values in the Tarsus_cm column that are less than 6 cm.

Hint: think about how the commands should be ordered to produce this data frame!

Solution

hawks_tarsus_cm <- hawks %>%
    mutate(Tarsus_cm = Tarsus / 10) %>%
    filter(Tarsus_cm < 6) %>%
    select(Species, Tarsus_cm)

Creating your own functions

Although there are many functions provided by R and its third-party packages, situations often arise when it is useful to write custom functions. Functions allow you automate common tasks and reduces the risk that you introduce errors in your code. If you find yourself copying and pasting the same block of code multiple times, you should consider wrapping that code block inside a function.

Let’s create a function for converting weight in kilograms to pounds:

kg_to_lb <- function(x) {
  lb  <-  x * 2.20462262
  return(lb)
}

We define kg_to_lb by assigning it to the output of function. The list of argument names are contained within parentheses. Next, the body of the function – the statements that are executed when it runs – is contained within curly braces ({}). The statements in the body are indented by two spaces, which makes the code easier to read but does not affect how the code operates.

When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a return statement to send a result back to whoever asked for it.

Automatic Returns

In R, it is not necessary to include the return statement. R automatically returns whichever variable is on the last line of the body of the function. While in the learning phase, we will explicitly define the return statement.

Let’s try running our function. Calling our own function is no different from calling any other function:

# Convert a single value
kg_to_lb(57.5)
[1] 126.7658
# Convert multiple values in a vector
kg_to_lb(c(48, 57.5, 52))
[1] 105.8219 126.7658 114.6404

Challenge 3.3

Use the function kg_to_lb() above to create a new column in the hawks data frame with the body weight expressed in pounds.

Solution

hawks %>%
    mutate(Weight_lb = kg_to_lb(Weight / 1000))

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:

hawks %>%
  group_by(Sex) %>%
  summarize(mean = mean(Weight, na.rm = TRUE))
# A tibble: 3 × 2
  Sex    mean
  <chr> <dbl>
1 F      257.
2 M      174.
3 <NA>  1090.

The argument na.rm is used to exclude NA values before computing the mean.

You can also group by multiple columns:

hawks %>%
  group_by(Species, Sex) %>%
  summarize(mean = mean(Weight, na.rm = TRUE))
# A tibble: 9 × 3
# Groups:   Species [3]
  Species Sex    mean
  <chr>   <chr> <dbl>
1 CH      F      490.
2 CH      M      348.
3 CH      <NA>   402 
4 RT      F     1147.
5 RT      M     1080 
6 RT      <NA>  1094.
7 SS      F      175.
8 SS      M      119.
9 SS      <NA>    95 

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:

hawks %>%
  group_by(Species, Sex) %>%
  summarize(mean = mean(Weight, na.rm = TRUE),
            min = min(Weight, na.rm = TRUE))
# A tibble: 9 × 4
# Groups:   Species [3]
  Species Sex    mean   min
  <chr>   <chr> <dbl> <dbl>
1 CH      F      490.    56
2 CH      M      348.   155
3 CH      <NA>   402    324
4 RT      F     1147.  1120
5 RT      M     1080   1080
6 RT      <NA>  1094.   101
7 SS      F      175.    92
8 SS      M      119.    85
9 SS      <NA>    95     95

It is sometimes useful to rearrange the result of a query to inspect the values. For instance, we can sort on min to put the lowest numbers first:

hawks %>%
  group_by(Species, Sex) %>%
  summarize(mean = mean(Weight, na.rm = TRUE),
            min = min(Weight, na.rm = TRUE)) %>% 
  arrange(min)
# A tibble: 9 × 4
# Groups:   Species [3]
  Species Sex    mean   min
  <chr>   <chr> <dbl> <dbl>
1 CH      F      490.    56
2 SS      M      119.    85
3 SS      F      175.    92
4 SS      <NA>    95     95
5 RT      <NA>  1094.   101
6 CH      M      348.   155
7 CH      <NA>   402    324
8 RT      M     1080   1080
9 RT      F     1147.  1120

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:

hawks %>%
  group_by(Species, Sex) %>%
  summarize(mean = mean(Weight, na.rm = TRUE),
            min = min(Weight, na.rm = TRUE)) %>% 
  arrange(min) %>% 
  arrange(desc(min))
# A tibble: 9 × 4
# Groups:   Species [3]
  Species Sex    mean   min
  <chr>   <chr> <dbl> <dbl>
1 RT      F     1147.  1120
2 RT      M     1080   1080
3 CH      <NA>   402    324
4 CH      M      348.   155
5 RT      <NA>  1094.   101
6 SS      <NA>    95     95
7 SS      F      175.    92
8 SS      M      119.    85
9 CH      F      490.    56

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:

hawks %>%
  count(Sex) 
# A tibble: 3 × 2
  Sex       n
  <chr> <int>
1 F       174
2 M       158
3 <NA>    576

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, hawks %>% count(Sex) is equivalent to:

hawks %>%
  group_by(Sex) %>%
  summarize(n = n())
# A tibble: 3 × 2
  Sex       n
  <chr> <int>
1 F       174
2 M       158
3 <NA>    576

We can also combine count() with other functions such as filter(). Here we will count the number of each species with weights above 800 g.

hawks %>%
  filter(Weight > 500) %>%
  count(Species)
# A tibble: 3 × 2
  Species     n
  <chr>   <int>
1 CH         19
2 RT        566
3 SS          2

The example above shows the use of count() to count the number of rows/observations for one factor (i.e., Species). If we wanted to count combination of factors, such as Species and Sex, we would specify the first and the second factor as the arguments of count():

hawks %>%
  filter(Weight > 500) %>%
  count(Species, Sex)
# A tibble: 6 × 3
  Species Sex       n
  <chr>   <chr> <int>
1 CH      F        17
2 CH      M         2
3 RT      F         3
4 RT      M         1
5 RT      <NA>    562
6 SS      M         2

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 sex and (ii) in descending order of the count:

hawks %>%
  filter(Weight > 500) %>%
  count(Species, Sex) %>% 
  arrange(Sex, desc(n))
# A tibble: 6 × 3
  Species Sex       n
  <chr>   <chr> <int>
1 CH      F        17
2 RT      F         3
3 CH      M         2
4 SS      M         2
5 RT      M         1
6 RT      <NA>    562

Challenge 3.4

  • For each year in the hawks data frame, how many captured birds have a weigh greater than 500 g?

Solution

hawks %>%
 filter(Weight > 500) %>%
 count(Year)
# A tibble: 12 × 2
    Year     n
   <dbl> <int>
 1  1992    33
 2  1993    28
 3  1994    90
 4  1995    56
 5  1996    14
 6  1997    45
 7  1998    26
 8  1999    57
 9  2000    82
10  2001    37
11  2002    61
12  2003    58
  • Use group_by() and summarize() to find the mean and standard deviation of the weight for each species and sex.

    Hint: calculate the standard deviation with the sd() function.

Solution

hawks %>%
    group_by(Species, Sex) %>%
    summarize(mean = mean(Weight),
              stdev = sd(Weight))
# A tibble: 9 × 4
# Groups:   Species [3]
  Species Sex    mean stdev
  <chr>   <chr> <dbl> <dbl>
1 CH      F      490. 183. 
2 CH      M      348.  99.1
3 CH      <NA>   402  110. 
4 RT      F     1147.  46.2
5 RT      M     1080   NA  
6 RT      <NA>    NA   NA  
7 SS      F       NA   NA  
8 SS      M       NA   NA  
9 SS      <NA>    95   NA  

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.

We will conclude this episode by generating a CSV file with a small dataset that contain only measurements for Red-tailed hawk females:

# Filter out observations
hawks_rt_f <- hawks %>% 
  filter(Species == "RT" & Sex == "F")

# Write data frame to CSV
write_csv(hawks_rt_f, file = "data_processed/Hawks_Red-Tailed_female.csv")