在R中做数据透视表的另一种方法 [英] Another way to do pivot table in R

查看:592
本文介绍了在R中做数据透视表的另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据集如下:

> 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

然后是某些变量的均值:

Then there is a code count mean of certain variables:

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

那么我需要执行以下输出:

Then I need to perform an output like below:

      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)

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

The output is same. My question: is there anyway to perform the same output with the different way?

这是我的课程,但是我的提交被拒绝了。我不知道为什么,但是我已经问过这个问题。

This is my a course but my submission was rejected. I do not know why but I had ask the about this.

请告知

推荐答案

一个选项是首先聚集 ,然后按'Var'和 summerise 分组以得到平均值'Val'

One option will be to gather first, group by 'Var' and summarise to get the mean of 'Val'

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

这篇关于在R中做数据透视表的另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆