-2

I have the following dataset as of now:

data.frame(Time = 208.8639, Passes = 84.52101, 
           Tackles = 4.191597, Saves = 0.6672269)
#>       Time   Passes  Tackles     Saves
#> 1 208.8639 84.52101 4.191597 0.6672269

I need to convert this to the following:

#>       var        mean
#> 1    Time 208.8639000
#> 2  Passes  84.5210100
#> 3 Tackles   4.1915970
#> 4   Saves   0.6672269

I'm facing problems when trying to give the column name "var" after using the "transpose" function. I tried using the "mutate" function as well. I need to use 'dplyr' functions here. Can someone help out please? Thanks

Abhishek
  • 11
  • 2

2 Answers2

1

you could use the following code:

### your data
my_df <- data.frame(Time = 208.8639, Passes = 84.52101, 
                    Tackles = 4.191597, Saves = 0.6672269)

library(tibble)

# transpose and keep data.frame
my_df2 <- as.data.frame(t(my_df))
names(my_df2) <- "mean"

# use the tibble function
rownames_to_column(my_df2, var = "var")

      var        mean
1    Time 208.8639000
2  Passes  84.5210100
3 Tackles   4.1915970
4   Saves   0.6672269
KoenV
  • 4,113
  • 2
  • 23
  • 38
1

Two ways: one with reshape2::melt() and one with tidyr::gather()

library(tidyverse)
df <- data.frame(Time = 208.8639, Passes = 84.52101, Tackles = 4.191597, Saves = 0.6672269)

# with reshape2::melt
reshape2::melt(df, variable.name = "var", value.name = "mean")
#> No id variables; using all as measure variables
#>       var        mean
#> 1    Time 208.8639000
#> 2  Passes  84.5210100
#> 3 Tackles   4.1915970
#> 4   Saves   0.6672269


# with tidyr::gather()
df %>% gather(var, mean)
#>       var        mean
#> 1    Time 208.8639000
#> 2  Passes  84.5210100
#> 3 Tackles   4.1915970
#> 4   Saves   0.6672269
Uwe
  • 41,420
  • 11
  • 90
  • 134
jrlewi
  • 486
  • 3
  • 8
  • Thanks this did work. Can this be solved using 'dplyr' functions? – Abhishek Dec 24 '17 at 14:42
  • maybe - but dplyr is more about 'munging' data and tidyr is more about 'tidying' data - I think your example fits more into the tidying realm than the munging realm...for more on tidyr see https://blog.rstudio.com/2014/07/22/introducing-tidyr/. Btw thanks for making a reprex...will update my answer with your exact data. – jrlewi Dec 24 '17 at 14:48