'Specify order after gather and spread

I want to keep the order of the output variables the same as the order they were created in the mutate statement. How do I accomplish this? It seems to be reordering alphabetically. Thanks!

df%>%
  mutate(
    twinkie= var1/60,
    peanut= var2/60,
    apple= var3/60,
    cheese= var4/60
  ) %>%
  group_by(store, associate)%>%
  summarise(
    twinkie=mean(twinkie),
    peanut = round(mean(peanut),
    apple = round(mean(apple),1),
    cheese = round(mean(cheese),1))
  %>%gather(Metric, value, -store, -associate)%>%spread(associate, value)


Solution 1:[1]

Convert the gathered Metric to a factor with the desired ordering. After gather, the values of Metric will be in the order in which you created them. You can then use the unique function to set this order as the order of the levels in Metric. For example:

library(tidyverse)

# Fake data
set.seed(2)
df = replicate(4, rnorm(30)) %>% 
  as.tibble %>% 
  mutate(store=sample(LETTERS[1:3],30,replace=TRUE),
         associate=sample(letters[1:4],30,replace=TRUE))

df %>%
  group_by(store, associate) %>%
  summarise(
    twinkie=mean(V1/60),
    peanut = round(mean(V2/60)),
    apple = round(mean(V3/60),1),
    cheese = round(mean(V4/60),1)) %>%
  gather(Metric, value, -store, -associate) %>% 
  mutate(Metric = factor(Metric, levels=unique(Metric))) %>% 
  spread(associate, value)
   store  Metric         a         b         c         d
1      A twinkie 0.1871809 0.1466679 0.1645085 0.1661182
2      A  peanut 0.0000000 0.0000000 0.0000000 0.0000000
3      A   apple 0.2000000 0.1000000 0.2000000 0.2000000
4      A  cheese 0.2000000 0.2000000 0.2000000 0.2000000
5      B twinkie 0.1635126 0.1865576 0.1823273 0.1857983
6      B  peanut 0.0000000 0.0000000 0.0000000 0.0000000
7      B   apple 0.2000000 0.1000000 0.2000000 0.1000000
8      B  cheese 0.2000000 0.2000000 0.2000000 0.2000000
9      C twinkie 0.1776549 0.1635294 0.1667490 0.1585236
10     C  peanut 0.0000000 0.0000000 0.0000000 0.0000000
11     C   apple 0.2000000 0.2000000 0.1000000 0.2000000
12     C  cheese 0.2000000 0.2000000 0.2000000 0.2000000

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1