[R] Syntax Check: rshape2 melt()
Nordlund, Dan (DSHS/RDA)
NordlDJ at dshs.wa.gov
Thu Oct 27 20:38:51 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 11:17 AM
> To: r-help at r-project.org
> Subject: Re: [R] Syntax Check: rshape2 melt()
>
> On Thu, 27 Oct 2011, Nordlund, Dan (DSHS/RDA) wrote:
>
> > You should be able to get what you want using the dcast function (I
> think).
> >
> > test.melted <- melt(tds.anal)
> > dcast(test.melted, site + sampdate ~ param)
>
> Dan,
>
> I don't think the data frame melted properly. I tried the dcast()
> but
> sampdate is not found:
>
> c.tds.anal <- dcast(m.tds.anal, site + sampdate ~ param)
> Error in eval(expr, envir, enclos) : object 'sampdate' not found
>
> Perhaps I still need to better understand the parameters in the
> melt()
> function.
>
> Rich
>
Rich,
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
Then ran the following code
> library(reshape2)
> 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
> dcast(melt(tds.anal), site + sampdate ~ param)
Using site, sampdate, param as id variables
site sampdate Ca Cl Cond Mg SO4 TDS
1 JCM-10B 2007-06-21 79 114 NA NA NA NA
2 STC-FS 1996-06-14 NA NA 280 NA NA NA
3 UDS-O 2006-12-06 NA NA NA NA NA 10800
4 UDS-O 2007-10-04 NA NA NA 1620 7580 NA
>
So you can see that at least it worked for me. Can you show us the actual output you get when running the melt and dcast functions on a sample of your data? I am not sure why sampdate is not found since it appears to be in your original sample data.
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