[R] Syntax Check: rshape2 melt()
Nordlund, Dan (DSHS/RDA)
NordlDJ at dshs.wa.gov
Thu Oct 27 18:48:52 CEST 2011
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Rich Shepard
> Sent: Thursday, October 27, 2011 8:26 AM
> To: r-help at r-project.org
> Subject: [R] Syntax Check: rshape2 melt()
>
>
> 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
>
Rich,
What I think you want is as simple as
test.melted <- melt(test)
wanted <- cast(test.melted, site + sampdate ~ param)
Hope this is helpful,
Dan
Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204
More information about the R-help
mailing list