Another way to do pivot table in R

孤街醉人 提交于 2019-12-12 11:06:12

问题


I have data set like below:

> 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))

and the output is:

> 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

I tried to do like this:

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.

Please advise


回答1:


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))



回答2:


Another option is to transpose your output wc_3, as follows:

result <- as.data.frame(t(w_c))

Set the name of your "mean" variable:

names(result)[1] <- "mean"

The names of the columns from wc_3 have become rownames in 'result', so we need to get these as values of the column "var":

result$var <- rownames(result)

Set the rownames in our 'result' table as NULL:

rownames(result) <- NULL

Interchange the order of columns:

result <- result[,c(2,1)]



来源:https://stackoverflow.com/questions/39656670/another-way-to-do-pivot-table-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!