Pivot table on R using `dplyr` or` tidyr`

I have a dataset as shown 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 the average number of codes for some variables:

 wc_3 <- worldcup %>% select(Time, Passes, Tackles, Saves) %>% summarize(Time = mean(Time), Passes = mean(Passes), Tackles = mean(Tackles), Saves = mean(Saves)) 

and output:

 > wc_3 Time Passes Tackles Saves 1 208.8639 84.52101 4.191597 0.6672269 

Then I need to execute the output as 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 the same. My question is: is there a way to make the same conclusion in a different way?

This is my course, but my submission was rejected. I do not know why, but I asked about it.

Please inform

+5
source share
2 answers

One option would consist of gather , first using "Var" and summarise to get mean in "Val"

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

Another option is to transpose the output of wc_3 as follows:

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

Name your "middle" variable:

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

The column names from wc_3 became the names of the growths in the "result", so we need to get them as the values ​​of the "var" column:

result$var <- rownames(result)

Set the growth names in our result table as NULL:

rownames(result) <- NULL

Reorder columns:

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

0
source

All Articles