How to collapse (melt) a data frame with pre specified columns

364 views Asked by At

I have the following data frame:

df <- structure(list(Setno = structure(c(1L, 1L, 1L), .Label = "set4", class = "factor"),
    Organ = structure(c(1L, 1L, 1L), .Label = "LN", class = "factor"),
    Adjn = structure(c(1L, 1L, 1L), .Label = "FOO", class = "factor"),
    Module_number = 1:3, Up_Count = c(2L, 0L, 0L), Down_count = c(1L,
    8L, 6L)), .Names = c("Setno", "Organ", "Adjn", "Module_number",
"Up_Count", "Down_count"), row.names = c(NA, 3L), class = "data.frame")

That looks like this

  Setno Organ Adjn Module_number Up_Count Down_count
1  set4    LN  FOO             1        2          1
2  set4    LN  FOO             2        0          8
3  set4    LN  FOO             3        0          6

What I want do to is to melt or collapse the data based on Up_Count and Down_count yielding this:

 Setno Organ Adjn Category Module_number Count
  set4    LN  FOO     Up_count        1     2   
  set4    LN  FOO     Up_count        2     0 
  set4    LN  FOO     Up_count        3     0
  set4    LN  FOO     Down_count      1     2   
  set4    LN  FOO     Down_count      2     8 
  set4    LN  FOO     Down_count      3     6

I tried this but didn't give what I want:

> library(reshape)
> melt(df)
Using Setno, Organ, Adjn as id variables
  Setno Organ Adjn      variable value
1  set4    LN  FOO Module_number     1
2  set4    LN  FOO Module_number     2
3  set4    LN  FOO Module_number     3
4  set4    LN  FOO      Up_Count     2
5  set4    LN  FOO      Up_Count     0
6  set4    LN  FOO      Up_Count     0
7  set4    LN  FOO    Down_count     1
8  set4    LN  FOO    Down_count     8
9  set4    LN  FOO    Down_count     6

What's the right way to do it?

0

There are 0 answers