concept gather() in category R

appears as: gather()
Machine Learning with R, the tidyverse, and mlr

This is an excerpt from Manning's book Machine Learning with R, the tidyverse, and mlr.

To convert this untidy tibble into its tidy counterpart, we can use tidyr’s gather() function. The gather() function takes the data as its first argument. The key argument defines the name of the new variable that will represent the columns we are “gathering.” In this case, the columns we are gathering are named Month0, Month3, and Month6, so we call the new column that will hold these keys Month. The value argument defines the name of the new variable that will represent the data from the columns we are gathering. In this case, the values were BMI measurements, so we call the new column that will represent these values BMI. The final argument is a vector defining which variables to gather and convert into the key-value pairs. By using -Patient, we are telling gather() to use all the variables except the identifying variable, Patient.

Listing 2.15. Tidying data with the gather() function
tidyPatientData <- gather(patientData, key = Month,
                          value = BMI, -Patient)

tidyPatientData

# A tibble: 9 x 3
  Patient Month    BMI
  <chr>   <chr>  <dbl>
1 A       Month0    21
2 B       Month0    17
3 C       Month0    29
4 A       Month3    20
5 B       Month3    21
6 C       Month3    27
7 A       Month6    21
8 B       Month6    22
9 C       Month6    23
  • The tidyr package provides the important function gather(), which lets you easily convert untidy data into tidy format. The opposite of this function is spread(), which converts tidy data into wide format.