Skip to main content

3. Data wrangling and visualization

R packages

Loading packages

In the first session, you installed R packages used in this course. Installed packages are not available automatically: you have to load them with library() in every new R session and in every markdown file that uses them. Put these calls at the top of your script or markdown file, so that you see at a glance which packages it needs. In this lab, we use the following packages:

library(ggplot2)   # Visualization
library(cowplot)   # Combining and arranging plots with plot_grid
library(tidyr)     # Reshape data
library(dplyr)     # Manipulating data

Namespace

Different packages can contain functions with the same name. For example, both dplyr and the base R package stats provide a function called filter(), but they serve different purposes.

Use the :: operator to specify which package’s function you want to call:

dplyr::filter(trees, height > 30)  # Select rows of a data frame
stats::filter(x, filter = rep(1/3, 3))  # Apply a time-series filter

This notation is called namespace notation. It allows you to call a function from a specific package without ambiguity, even if several packages provide functions with the same name.

Data wrangling

Preparing data for analysis can take a substantial amount of time. Following the principles of tidy data helps simplify this process (Wickham, 2014):

  • Each variable forms a column.
  • Each observation forms a row.
  • Each type of observational unit forms a table.

Real-world datasets often violate these principles and require cleaning or restructuring before analysis. Common problems include:

  • Column headers contain values rather than variable names.
  • Multiple variables are stored in a single column.
  • Variables are spread across rows and columns.
  • Different types of observational units are stored in the same table.
  • A single type of observational unit is spread across multiple tables.

In R, the dplyr and tidyr packages provide tools to address these problems. dplyr supports data manipulation, including filtering, selecting, summarizing, and joining data. tidyr focuses on data restructuring, such as pivoting tables and separating or combining columns. Together, they help transform raw data into a tidy format suitable for analysis and visualization. For a quick reference, see the following cheat sheets for tidyr and dplyr.

Reshape

Consider an example in which temperature was recorded on three days for each of three plots (id). The data are stored in a wide format, with a separate column for each day. This violates the tidy data principle that each variable should form a column. Instead, the day is encoded in the column names, and temperature measurements are spread across multiple columns. Pivoting the data into long format resolves this issue by storing the day and temperature in separate columns, with one row for each plot and day (see Figure 5.1).

Figure 5.1: Pivoting a temperature table from wide to long format.

We can use tidyr’s pivot_longer() to reshape the data from wide to long format, gathering the day names into a Day column and their temperature values into a Temperature column. The id column identifies each plot and remains unchanged. We therefore exclude it from pivoting using cols = -id. Alternatively, we can explicitly select the measurement columns with cols = c(Monday, Tuesday, Wednesday). When converting to long format, the selected column names are stored in a new column, Day, and their values in Temperature. The resulting long-format table contains one row for each plot and day, as shown in Figure 5.1.

temperatures_long <- pivot_longer(temperatures_wide,
                                  cols = -id,
                                  names_to = "Day",
                                  values_to = "Temperature")

To return to the wide table, pivot_wider() uses the day names in Day as column names and places each measurement from Temperature into the matching column. The argument id_cols specifies which columns identify the rows: rows of the long table with the same values in these columns are combined into one row.

temperatures_wide <- pivot_wider(temperatures_long,
                                 id_cols = id,
                                 names_from = Day,
                                 values_from = Temperature)

In this example, we could leave out id_cols. By default, pivot_wider() uses all columns not named in names_from or values_from to identify the rows. The only such column is the plot id, so we still get one row per plot. This works because all measurements of a plot share the same id, so id tells us which measurements belong together.

However, the default fails if the table contains a column that does not tell us which measurements belong together. To illustrate, we add the column key, which gives each measurement a unique number. If we now leave out id_cols, key also identifies the rows. Because each of its values occurs only once, no rows are combined, and the wide table has one row per measurement and many missing values:

temperatures_long$key <- 1:nrow(temperatures_long)
pivot_wider(temperatures_long,
            names_from = Day,
            values_from = Temperature)
# A tibble: 9 × 5
     id   key Monday Tuesday Wednesday
  <dbl> <int>  <dbl>   <dbl>     <dbl>
1     1     1     10      NA        NA
2     1     2     NA      15        NA
3     1     3     NA      NA        12
4     2     4      8      NA        NA
5     2     5     NA       9        NA
6     2     6     NA      NA        11
7     3     7     14      NA        NA
8     3     8     NA      18        NA
9     3     9     NA      NA        16

With id_cols = id, as above, we would again get one row per plot, and key would be dropped.

Yields example

The yields dataset, adapted from Crawley’s The R Book (2012), contains yield measurements for three soil types: sand, clay, and loam. Each soil type has ten observations. The plotid column identifies the observations; it does not imply that measurements with the same ID across soil types come from the same physical plot. The dataset is provided in wide format.

yields <- read.table("data/yields2.txt", sep = ";", header = TRUE)
yields[1:5, ]
  plotid sand_fine clay_fine loam_fine sand_coarse clay_coarse loam_coarse
1      1         6        17        13           9          18          15
2      2        10        15        16          10          15          18
3      3         8         3         9           9           3           9
4      4         6        11        12           7          11          12
5      5        14        14        15          14          16          15

To analyze and visualize yield by soil type, we first need to reshape the data into long format using pivot_longer(). We exclude the plotid column; then we reshape the soil names into a new column soiltype and the values into a new column yield.

yields_tidy <- tidyr::pivot_longer(yields,
                                   cols= -plotid,
                                   names_to = "soilgroup",
                                   values_to = "yield")
yields_tidy
# A tibble: 60 × 3
   plotid soilgroup   yield
    <int> <chr>       <int>
 1      1 sand_fine       6
 2      1 clay_fine      17
 3      1 loam_fine      13
 4      1 sand_coarse     9
 5      1 clay_coarse    18
 6      1 loam_coarse    15
 7      2 sand_fine      10
 8      2 clay_fine      15
 9      2 loam_fine      16
10      2 sand_coarse    10
# ℹ 50 more rows

separate()

The soilgroup column contains two variables: soiltype and grain size. We can automatically split that column into two column using the separate() function:

yields_tidy <- separate(yields_tidy,
                        col = soilgroup,
                        into = c("soiltype", "grain"),
                        sep = "_",
                        remove = FALSE)
yields_tidy
# A tibble: 60 × 5
   plotid soilgroup   soiltype grain  yield
    <int> <chr>       <chr>    <chr>  <int>
 1      1 sand_fine   sand     fine       6
 2      1 clay_fine   clay     fine      17
 3      1 loam_fine   loam     fine      13
 4      1 sand_coarse sand     coarse     9
 5      1 clay_coarse clay     coarse    18
 6      1 loam_coarse loam     coarse    15
 7      2 sand_fine   sand     fine      10
 8      2 clay_fine   clay     fine      15
 9      2 loam_fine   loam     fine      16
10      2 sand_coarse sand     coarse    10
# ℹ 50 more rows

By default, separate() removes the original column. To keep it, for example because you still need the combined identifier later, set remove = FALSE.

yields_soil <- pivot_longer(yields,
                            cols = -plotid,
                            names_to = "soil",
                            values_to = "yield")
separate(yields_soil,
         col = soil,
         into = c("soiltype", "grain"),
         sep = "_",
         remove = FALSE)
# A tibble: 60 × 5
   plotid soil        soiltype grain  yield
    <int> <chr>       <chr>    <chr>  <int>
 1      1 sand_fine   sand     fine       6
 2      1 clay_fine   clay     fine      17
 3      1 loam_fine   loam     fine      13
 4      1 sand_coarse sand     coarse     9
 5      1 clay_coarse clay     coarse    18
 6      1 loam_coarse loam     coarse    15
 7      2 sand_fine   sand     fine      10
 8      2 clay_fine   clay     fine      15
 9      2 loam_fine   loam     fine      16
10      2 sand_coarse sand     coarse    10
# ℹ 50 more rows

Now, we can plot yield by soil type:

ggplot(yields_tidy, aes(x = soiltype, y = yield)) +
  geom_boxplot()

..or by soil type and grain size:

ggplot(yields_tidy, aes(x = soiltype, y = yield, fill = grain)) +
  geom_boxplot()

Pipes

Data wrangling often involves several transformation steps that build on one another. Pipes allow us to chain operations together in a readable sequence, making the flow of data easier to follow. The base R pipe (|>), introduced in R 4.1.0, passes the result on its left as the first argument to the function on its right. For example, x |> f(y) is equivalent to f(x, y). The dplyr and tidyr packages work seamlessly with the base pipe, which we use throughout this course. You may also encounter the pipe %>% from the magrittr package in older R code.

yields_tidy <- yields |>
  pivot_longer(cols= -plotid,
               names_to = "soiltype",
               values_to = "yield") |>
  separate(col = soiltype,
           into = c("soiltype", "grain"),
           sep = "_")

Mutating new variables

If we want to create a new variable (column), we can use the mutate() function:

yields_tidy <- yields_tidy |>
  mutate(yield_log = log(yield),
         yield_log10 = log10(yield))

yields_tidy[1:3, ]
# A tibble: 3 × 6
  plotid soiltype grain yield yield_log yield_log10
   <int> <chr>    <chr> <int>     <dbl>       <dbl>
1      1 sand     fine      6      1.79       0.778
2      1 clay     fine     17      2.83       1.23 
3      1 loam     fine     13      2.56       1.11 

Summaries

To summarize one or more variables, we can use summarize(). Here, we calculate the mean and median yield. The function n() counts the number of rows. It takes no arguments and also counts rows with missing values. To count the number of unique values of a variable instead, use n_distinct(). For example, n_distinct(soiltype) returns 3 here, one for each soil type.

yields_tidy_summary <- yields_tidy |>
  summarize(yield_mean = mean(yield),
            yield_median = median(yield),
            n_samples = n(),
            n_soiltype = n_distinct(soiltype))

yields_tidy_summary
# A tibble: 1 × 4
  yield_mean yield_median n_samples n_soiltype
       <dbl>        <dbl>     <int>      <int>
1       12.4           12        60          3

Grouping

We can calculate new variables and summarize data either across the entire dataset or within specific groups. For example, we might calculate the mean and median yield for each combination of soil type and grain class.

First, group_by() defines how the observations should be grouped for subsequent operations. It does not change the rows or values in the data frame. Instead, it adds grouping information that tells functions such as summarize() to operate separately on each group. Here, the data are grouped by soiltype and grain, so each unique combination forms a separate group.

The function summarize() then calculates the requested statistics for each group, so n() now gives the number of observations in each group. The argument .groups = "drop" removes the grouping information from the resulting data frame, so subsequent operations treat it as an ordinary, ungrouped data frame.

yields_tidy_summary <- yields_tidy |>
  group_by(soiltype, grain) |>
  summarize(yield_mean = mean(yield),
            yield_median = median(yield),
            n = n(),
            .groups = "drop")

yields_tidy_summary
# A tibble: 6 × 5
  soiltype grain  yield_mean yield_median     n
  <chr>    <chr>       <dbl>        <dbl> <int>
1 clay     coarse       12.4         13      10
2 clay     fine         11.5         12      10
3 loam     coarse       15.5         15      10
4 loam     fine         14.3         14.5    10
5 sand     coarse       10.6         10      10
6 sand     fine          9.9          9.5    10

We also can use the mutate() function within groups, e.g. for centering the yields within groups:

yields_tidy <- yields_tidy |>
  group_by(soiltype, grain) |>
  mutate(yield_centered = yield - mean(yield))  |> 
  ungroup()

yields_tidy
# A tibble: 60 × 7
   plotid soiltype grain  yield yield_log yield_log10 yield_centered
    <int> <chr>    <chr>  <int>     <dbl>       <dbl>          <dbl>
 1      1 sand     fine       6      1.79       0.778        -3.9   
 2      1 clay     fine      17      2.83       1.23          5.5   
 3      1 loam     fine      13      2.56       1.11         -1.3   
 4      1 sand     coarse     9      2.20       0.954        -1.6   
 5      1 clay     coarse    18      2.89       1.26          5.6   
 6      1 loam     coarse    15      2.71       1.18         -0.5   
 7      2 sand     fine      10      2.30       1             0.1000
 8      2 clay     fine      15      2.71       1.18          3.5   
 9      2 loam     fine      16      2.77       1.20          1.7   
10      2 sand     coarse    10      2.30       1            -0.600 
# ℹ 50 more rows

Tibbles

Functions from dplyr that return a table return a tibble by default. A tibble is similar to a traditional R data frame but offers several improvements. For example, it displays the dimensions and column data types when printed and presents data in a more readable format in the console, especially for large datasets.

head(yields_tidy)
# A tibble: 6 × 7
  plotid soiltype grain  yield yield_log yield_log10 yield_centered
   <int> <chr>    <chr>  <int>     <dbl>       <dbl>          <dbl>
1      1 sand     fine       6      1.79       0.778           -3.9
2      1 clay     fine      17      2.83       1.23             5.5
3      1 loam     fine      13      2.56       1.11            -1.3
4      1 sand     coarse     9      2.20       0.954           -1.6
5      1 clay     coarse    18      2.89       1.26             5.6
6      1 loam     coarse    15      2.71       1.18            -0.5

Filter observations

We can use filter() to select observations (rows) that meet specific conditions. For example, the following code retains only observations where grain is "fine":

yields_tidy_subset <- yields_tidy |>
  filter(grain == "fine")

Select columns

We can use select() to choose which variables (columns) to retain in a dataset. To exclude variables, we prefix their names with a minus sign (-). In the following example, we remove yield_log10 and yield_log, while keeping all other columns in yields_tidy:

yields_tidy_subset <- yields_tidy |>
  select(-yield_log10, -yield_log)

The select() function also supports helper functions for selecting columns based on their names, such as starts_with(), ends_with(), and contains(). These are particularly useful when working with datasets that contain many variables or follow consistent naming conventions. For a complete overview of column-selection options, see the dplyr documentation for select().

ggplot2

The base R graphics system can be used to visualize complex datasets and relationships, but creating more elaborate visualizations often requires writing more code. The ggplot2 package provides a powerful alternative. It uses a consistent approach to building plots by combining data, aesthetic mappings, and graphical layers. Although ggplot2 has a different syntax and workflow from base R graphics, it makes complex visualizations easier to construct and customize.

When creating a plot with ggplot2, we typically specify three key components:

  • Data: The data argument in ggplot() specifies the dataset used for the plot. Individual geom_*() layers can also use their own datasets.

  • Aesthetics: The aes() function maps variables in the dataset to visual properties of the plot, such as the x- and y-axes, colour, and shape.

  • Layers: At least one layer is needed to define how the data are displayed. Layers are usually added using geometric functions, such as geom_point() for scatter plots, geom_histogram() for distributions, and geom_boxplot() for comparing distributions.

The following examples illustrate how to construct familiar plots using ggplot2.

ggplot(data = airquality, aes(x = Ozone)) +
  geom_histogram()

ggplot(data = airquality, aes(x = Ozone, y = Temp)) + 
  geom_point()

ggplot(data = airquality, aes(x = factor(Month), y = Ozone)) +
  geom_boxplot()

The + operator adds layers to a plot. Each layer specifies a geometric representation and can have its own aesthetic mappings.

Visualizing groups

Mapping variables to visual properties such as colour, shape, and line type allows us to distinguish groups within a single plot. The aes() function connects variables in the dataset to these properties, making it possible to display additional information without creating separate plots.

For example, we can use colour to distinguish observations from different months:

ggplot(data = airquality, aes(x = Ozone, y = Temp, col = factor(Month))) +
  geom_point()

Here, factor(Month) treats month as a categorical variable, so each month receives a distinct colour. The same variable can be mapped to point shape:

ggplot(data = airquality, aes(x = Ozone, y = Temp, shape  = factor(Month))) +
  geom_point()

The linetype aesthetic can be used to group observations according to a variable and assign a different line type to each group.

ggplot(data = airquality, aes(x = Day, y = Temp, linetype = factor(Month))) +
  geom_line()

Line plots also support the group aesthetic, which specifies which observations should be connected to form a line, independently of their visual appearance. In the example above, each month has a single temperature trend, so mapping Month to `linetype. is sufficient to distinguish the monthly lines, An additional group mapping is unnecessary. The group aesthetic becomes useful, for example, when observations come from multiple weather stations and we want to draw a separate line for each station without distinguishing the lines by their appearance.

Some geometries, including histograms and boxplots, use the fill aesthetic to control the interior colour of graphical elements.

ggplot(data = airquality, aes(x = Ozone, fill = factor(Month))) +
  geom_histogram()

Scaling by numeric variables

Categorical variables can distinguish groups using colours, shapes, or line types. Numeric variables can be represented using continuous colour gradients or varying symbol sizes.

Factors can be used to define colors and symbols. Numeric variables can be displayed by varying symbol sizes and color gradients:

ggplot(data = airquality, aes(x = Ozone, y = Temp, col = Wind, size = Solar.R)) +
  geom_point()

Panel plots (faceting)

Panel plots display the same type of plot for different subsets of the data, allowing relationships to be examined separately for different groups.

In ggplot2, this can be done with facet_wrap(). The following example creates a separate panel for each month:

ggplot(data = airquality, aes(x = Ozone, y = Temp)) +
  geom_point() +
  facet_wrap(~Month)

By default, all panels use the same axis scales, making values comparable across panels. Setting scales = "free" allows each panel to use its own axis scales:

ggplot(data = airquality, aes(x = Ozone, y = Temp)) +
  geom_point() +
  facet_wrap(~Month, scales = "free")

Combining multiple layers

A ggplot can contain multiple layers, each with its own aesthetic mappings. A layer inherits the mappings specified in ggplot() unless they are overridden or additional mappings are supplied.

ggplot(data = airquality, aes(x = Day, y = Temp)) +
  geom_point(aes(size = Ozone)) +
  geom_line(aes(linetype = factor(Month)))

Here, the points represent daily temperatures, with point size indicating ozone concentration. The lines distinguish months by line type.

Axis labels and plot title

Use labs() to set axis labels and a plot title. It can also be used to specify legend titles.

ggplot(data = airquality, aes(x = Ozone, y = Temp, col = factor(Month))) +
  geom_point() +
  labs(x = "Ozone concentration [ppm]",
       y = "Temperature [°F]",
       title = "Relationship between Ozone und Temperature")

Combining multiple plots

The plot_grid() function from the cowplot package arranges multiple plots in a single graphic. First, create a plot object for each plot, then pass the objects to plot_grid().

plot1 <- ggplot(data = airquality, aes(x = Ozone, y = Temp)) + geom_point()
plot2 <- ggplot(data = airquality, aes(x = Ozone, y = Wind)) + geom_point()

cowplot::plot_grid(plot1, plot2, ncol = 2)

Exporting graphics

R can export graphics in formats such as PDF, TIFF, PNG, and JPEG. Use ggsave() to save a plot to a file. The path argument specifies the directory in which to save it; the directory must already exist.

p <- ggplot(data = airquality, aes(x = Ozone, y = Temp, col = factor(Month))) +
  geom_point()

ggsave(filename = "plot.pdf", plot = p, path = "Figures")

Base graphics

R’s base graphics provide a simple and convenient way to visualize data, particularly for quick exploratory analysis. They are available by default, without installing additional packages. The main functions include plot() for scatterplots and other types of plots, hist() for histograms, and boxplot() for boxplots. These functions can be customized with arguments to control titles, axis labels, colours, symbols, and other graphical properties.

hist(airquality[ , c("Ozone")])

plot(airquality[ , c("Ozone")], airquality[ , c("Temp")])

boxplot(airquality[ , c("Ozone")] ~ airquality[ , c("Month")])

References

Wickham, H., 2014. Tidy data. Journal of Statistical Software 59, 1–23. https://doi.org/10.18637/jss.v059.i10