gpt4 book ai didi

r - 收集和散布后指定顺序

转载 作者:行者123 更新时间:2023-12-02 09:12:28 25 4
gpt4 key购买 nike

我想保持输出变量的顺序与它们在 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)

最佳答案

将收集到的 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

关于r - 收集和散布后指定顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50593036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com