-1

This might possible be a duplicate question.

I am working with a dataset which is as shown below

Hunters <-  rnorm(20, 10,3)
Hoarders <- rnorm(20, 4, 5)
Truckers <- rnorm(20, 6, 2)
Ninja_Warriors <- rnorm(20, 8, 5)
Inventors   <-  rnorm(20, 5, 5)
y           <- rbinom(20, 1, 0.2)

df <- data.frame(cbind(y,Hunters, Hoarders, Truckers, Ninja_Warriors, Inventors ))

head(df)
  y   Hunters  Hoarders Truckers Ninja_Warriors   Inventors
  0 10.683681  2.436301 5.728774      12.072325  5.77553574
  0 11.795734  3.160194 7.224706       9.162267  3.02488425
  0  6.385799 -1.133548 7.074739       5.007134 -2.67054701
  0 13.949215  7.903503 4.648848       7.886313  4.71579763
  1 11.091341  7.700549 3.460969       6.728078  3.95914947
  0 14.187529  3.503359 4.416457       2.637822  0.06991962

I need help transforming this dataset to a long format like this

 Variable       Group     Value
 Hunters        0         10.683681
 Hoarders       0         2.436301
 Truckers       0         5.728774
 Ninja_Warriors 0         12.072325
 Inventors      0         5.77553574
 .              .          .
 .              .          . 
 .              .          .
 .              .          . 
Jill Sellum
  • 319
  • 2
  • 4
  • 14

1 Answers1

1

For instance, using reshape2:

library(reshape2)
library(dplyr)
melt(df, id.vars = "y", variable.name = "Variable", value.name = "Value") %>% rename(Group = y)
    Group          Variable       Value
1       0        Hunters  9.65692150
2       0        Hunters 10.17101981
3       0        Hunters  6.54119659
4       0        Hunters  8.14213268
5       0        Hunters  2.54939639

    ...

Alternatively, using tidyr:

library(tidyr)
gather(df, key=Variable, value=Value, -y ) %>% rename(Group = y)
    Group       Variable       Value
1       0        Hunters  9.65692150
2       0        Hunters 10.17101981
3       0        Hunters  6.54119659
4       0        Hunters  8.14213268
5       0        Hunters  2.54939639
...
coffeinjunky
  • 11,254
  • 39
  • 57