dplyr - 收集和传播后指定顺序

时间:2018-05-29 21:12:51

标签: r dplyr

我想保持输出变量的顺序与它们在mutate语句中创建的顺序相同。我该如何做到这一点?它似乎按字母顺序重新排序。谢谢!

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)

1 个答案:

答案 0 :(得分:4)

将收集的Metric转换为具有所需排序的因子。在gather之后,Metric的值将按照您创建它们的顺序排列。然后,您可以使用unique函数将此顺序设置为Metric中级别的顺序。例如:

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