r 从长到宽重塑

r long to wide reshape

这可能是一个重复的问题。

我正在使用如下所示的数据集

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

我需要帮助将此数据集转换为这样的长格式

 Variable       Group     Value
 Hunters        0         10.683681
 Hoarders       0         2.436301
 Truckers       0         5.728774
 Ninja_Warriors 0         12.072325
 Inventors      0         5.77553574
 .              .          .
 .              .          . 
 .              .          .
 .              .          . 

例如,使用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

    ...

或者,使用 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
...