[R] Syntax Check: rshape2 melt()

Rich Shepard rshepard at appl-ecosys.com
Thu Oct 27 17:26:07 CEST 2011


   This is my first excursion into using reshape2 and I want to ensure that
the melt() function call is syntactically correct.

   The unmodifed data frame is organized this way:

head(tds.anal)
       site   sampdate param quant
1    UDS-O 2006-12-06   TDS 10800
4   STC-FS 1996-06-14  Cond   280
7    UDS-O 2007-10-04    Mg  1620
9    UDS-O 2007-10-04   SO4  7580
19 JCM-10B 2007-06-21    Ca    79
20 JCM-10B 2007-06-21    Cl   114

   What I want looks like this:

     site    sampdate  TDS   Cond   Mg  Ca   Cl  Na  SO4
    UDS-O  2006-12-06  10800  NA   1620 NA   NA  NA  7580

with the actual data for each param, of course.

   I've read the reshape.pdf, reshape2.pdf, the ?melt help page, and the
?melt.data.frame help page. I'm still unclear on the differences among
measure.vars, variable.name, and value.name. After several attempts I have
what may be what the melted tds.anal should look like:

m.tds.anal <- melt(tds.anal, id.vars = c('site', 'sampdate', 'param'), \
measure.vars = 'quant', value.name = 'quant', na.rm = F)
> head(m.tds.anal)
      site   sampdate param variable quant
1   UDS-O 2006-12-06   TDS    quant 10800
2  STC-FS 1996-06-14  Cond    quant   280
3   UDS-O 2007-10-04    Mg    quant  1620
4   UDS-O 2007-10-04   SO4    quant  7580
5 JCM-10B 2007-06-21    Ca    quant    79
6 JCM-10B 2007-06-21    Cl    quant   114

   Is the melt() function call correct? Should the melted result look like
the unmelted ("long" form in Paul Dalgaard's book) data with the additional
'variable' column containing 'quant' for each row?

Rich



More information about the R-help mailing list