gpt4 book ai didi

r - 在 R 中做数据透视表的另一种方法

转载 作者:行者123 更新时间:2023-12-04 10:16:19 26 4
gpt4 key购买 nike

我有如下数据集:

> head(worldcup)
Team Position Time Shots Passes Tackles Saves
Abdoun Algeria Midfielder 16 0 6 0 0
Abe Japan Midfielder 351 0 101 14 0
Abidal France Defender 180 0 91 6 0
Abou Diaby France Midfielder 270 1 111 5 0
Aboubakar Cameroon Forward 46 2 16 0 0
Abreu Uruguay Forward 72 0 15 0 0

然后是某些变量的代码计数平均值:
wc_3 <- worldcup %>% 
select(Time, Passes, Tackles, Saves) %>%
summarize(Time = mean(Time),
Passes = mean(Passes),
Tackles = mean(Tackles),
Saves = mean(Saves))

输出是:
> wc_3
Time Passes Tackles Saves
1 208.8639 84.52101 4.191597 0.6672269

然后我需要执行如下输出:
      var           mean
Time 208.8638655
Passes 84.5210084
Tackles 4.1915966
Saves 0.6672269

我试着这样做:
wc_3 <- worldcup %>% 
select(Time, Passes, Tackles, Saves) %>%
summarize(Time = mean(Time),
Passes = mean(Passes),
Tackles = mean(Tackles),
Saves = mean(Saves)) %>%
gather(var, mean, Time:Saves, factor_key=TRUE)

输出是一样的。我的问题:有没有以不同的方式执行相同的输出?

这是我的类(class),但我的提交被拒绝了。我不知道为什么,但我问过这个。

请指教

最佳答案

一种选择是到 gather首先,按 'Var' 和 summarise 分组获取 mean '瓦尔'

library(dplyr)
library(tidyr)
worldcup %>%
gather(Var, Val, Time:Saves) %>%
filter(Var!= "Shots") %>%
group_by(Var) %>%
summarise(Mean = mean(Val))

关于r - 在 R 中做数据透视表的另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39656670/

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