0

I have a data table that looks like

Group 1   Group 2   Group 3   Label
  3         5         6        red
  4         2         8        green
  7         3         2        blue

and I want to put the values, headers and values from the Label column into columns so that the data looks like

3    red     group 1
5    red     group 2
6    red     group 3
4    green   group 1
2    green   group 2
8    green   group 3
7    blue    group 1
3    blue    group 2
2    blue    group 3

How can I go about doing this in R?

Thank you.

brad
  • 89
  • 7
  • Possible duplicate of [Reshaping data.frame from wide to long format](http://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) – jeremycg Nov 23 '15 at 22:13
  • 2
    try `library(tidyr); dat %>% gather(group, val, -Label)` – jeremycg Nov 23 '15 at 22:15

1 Answers1

0

An alternative in "reshape2" can be done like this:

if (!require(reshape2)) {install.packages("reshape2"); require(reshape2)}

df <- data.table(`Group 1`  = c(3, 4, 7), `Group 2` = c(5, 2, 3),
             `Group 3` = c(6, 8, 2), Label = c("red", "green", "blue"))
melt(df, id.vars = "Label")
thelatemail
  • 91,185
  • 12
  • 128
  • 188
entropium
  • 29
  • 4