[R] Syntax Check: rshape2 melt()

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Thu Oct 27 21:23:30 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 12:00 PM
> To: r-help at r-project.org
> Subject: Re: [R] Syntax Check: rshape2 melt()
> 
> On Thu, 27 Oct 2011, Nordlund, Dan (DSHS/RDA) wrote:
> 
> > I read in the sample data that you put in an earlier post.
> >
> >> tds.anal <- read.table('clipboard',header=TRUE)
> >> 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
> 
> Dan,
> 
>    In your 'tds.anal' is sampdate a factor or a date? Here it's a date:
> 
> str(tds.anal)
> 'data.frame':	11434 obs. of  4 variables:
>   $ site    : Factor w/ 143 levels "BC-0.5","BC-1",..: 134 127 134 134
> 73 73
> 91 91 91 91 ...
>   $ sampdate: Date, format: "2006-12-06" "1996-06-14" ...
>   $ param   : Factor w/ 7 levels "Ca","Cl","Cond",..: 7 3 4 6 1 2 4 5 1
> 4 ...
>   $ quant   : num  10800 280 1620 7580 79 114 301 27.5 381 274 ...
> 
>    I wonder if that's what's not working here.
> 
> > Then ran the following code
> >> melt(tds.anal)
> > Using site, sampdate, param as id variables
> >     site   sampdate param variable value
> > 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
> 
>    When I do this I see:
> 
> melt(tds.anal)
> Using site, param as id variables
>              site param variable     value
> 1          UDS-O   TDS sampdate 13488.000
> 2         STC-FS  Cond sampdate  9661.000
> 3          UDS-O    Mg sampdate 13790.000
> 4          UDS-O   SO4 sampdate 13790.000
> 5        JCM-10B    Ca sampdate 13685.000
> 6        JCM-10B    Cl sampdate 13685.000
> 
>    Notice there's no sampdate here.
> 
> Rich
> 
Rich,

You were right about sampdate as I read it in.  How about trying this on your data

>m.tds.anal <-  melt(tds.anal, id.vars = c('site', 'sampdate', 'param'), 
          variable.name = 'variable', na.rm = T, value.name = 'quant')

>wanted <- dcast(m.tds.anal, 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