Wrangling kittehs ๐Ÿˆ๐Ÿˆโ€โฌ›๐Ÿˆ๐Ÿˆโ€โฌ›๐Ÿ™€

In this brief example we look at why getting data into a tidy format is often a requirement for data wrangling and visualisation.

Begin by loading some packages:

library("readxl")
library("dplyr")

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library("tidyr")
library("ggplot2")

Next we load the weight data for Hansi and Apricot

cat_weights <- read_excel(
  "data/my-cats/hansi-apricot-weights.xlsx",
  col_types = rep("numeric", 2)
) |>
  janitor::clean_names()

LKook at the data to check everything is OK

cat_weights
# A tibble: 31 ร— 2
   hansi apricot
   <dbl>   <dbl>
 1  5.65   NA   
 2  5.25    3.15
 3  5.65    3.4 
 4  5.35    3.2 
 5  5.45    3.4 
 6  5.55    3.5 
 7  5.4     3.35
 8  5.5     3.05
 9  5.55    3.4 
10  5.25    3.25
# โ„น 21 more rows

If we wanted to filter data for a chosen cat, Apricot say, weโ€™d also be filtering out rows of data belonging to Hansi. Also, there is no variable in the data that I can use to reference a specific cat; this information is in the variable names. As such, this data set is not tidy.

We can make the data tidy by pivoting the data set. We want to go from this wide representation of the data to a longer representation โ€” weโ€™re effectively going to stack the two columns of weight data into a single column and create a new variable that identifies which row belongs to which of my cats. We do this with pivot_longer():

cat_long <- cat_weights |>
  pivot_longer(
    cols = everything(),    # which variables are we pivotting?
    names_to = "cat",       # name of variable to contain each cat's name
    values_to = "weight_kg" # name of the variable to hold the weights
  )

This results in:

cat_long
# A tibble: 62 ร— 2
   cat     weight_kg
   <chr>       <dbl>
 1 hansi        5.65
 2 apricot     NA   
 3 hansi        5.25
 4 apricot      3.15
 5 hansi        5.65
 6 apricot      3.4 
 7 hansi        5.35
 8 apricot      3.2 
 9 hansi        5.45
10 apricot      3.4 
# โ„น 52 more rows

Now we can use the cat variable to enhance any rgaphics we might produce of the data, e.g.

cat_long |>
  ggplot(
    aes(y = weight_kg, x = cat, colour = cat)
  ) +
  geom_boxplot() +
  geom_point(position = position_jitter(width = 0.1)) +
  labs(
    x = NULL, y = "Weight [kg]", colour = "Cat"
  )
Warning: Removed 1 row containing non-finite outside the scale range
(`stat_boxplot()`).
Warning: Removed 1 row containing missing values or values outside the scale range
(`geom_point()`).