Why is pivot_*() output ordered differently to gather()/spread()?

Is there a reason that the new pivot_*() functions in {tidyr} order their output differently to gather()/spread()? Am I missing something?

For example, the gather() output in the reprex below is ordered within 'year', but the pivot_longer() output is ordered within 'country'.

Context: I've considered updating the Software Carpentry course on dataframe manipulation with tidyr, given the changes to {tidyr} in version 1.0.0.

# Load {tidyr} >= 1.0.0
library(tidyr)

# Toy data set
data <- tibble(
  country = c("C", "A", "B"),
  X = c(3, 1, 2),
  Y = c(2, 1, 3)
)

# Data set before reshaping
data
#> # A tibble: 3 x 3
#>   country     X     Y
#>   <chr>   <dbl> <dbl>
#> 1 C           3     2
#> 2 A           1     1
#> 3 B           2     3

# Output is ordered by supplied year
gather(
  data, Y, X, 
  key = "year", value = "cases"
)
#> # A tibble: 6 x 3
#>   country year  cases
#>   <chr>   <chr> <dbl>
#> 1 C       Y         2
#> 2 A       Y         1
#> 3 B       Y         3
#> 4 C       X         3
#> 5 A       X         1
#> 6 B       X         2

# Output is ordered by supplied year, within country
pivot_longer(
  data, cols = c(Y, X),
  names_to = "year", values_to = "cases"
)
#> # A tibble: 6 x 3
#>   country year  cases
#>   <chr>   <chr> <dbl>
#> 1 C       Y         2
#> 2 C       X         3
#> 3 A       Y         1
#> 4 A       X         1
#> 5 B       Y         3
#> 6 B       X         2

Created on 2019-11-04 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.