[R] Syntax Check: rshape2 melt()

Rich Shepard rshepard at appl-ecosys.com
Thu Oct 27 23:40:47 CEST 2011


On Thu, 27 Oct 2011, Dennis Murphy wrote:

> # Define param so that all of its levels are represented:
> tds.a <- within(tds.a, {
>           param = factor(param, levels = c('TDS', 'Cond', 'Mg', 'Ca',
> 'Cl', 'Na', 'SO4'))
>           sampdate = as.Date(sampdate)  } )

Dennis,

   This produces an error:
tds.a <- within(tds.anal, {param = factor(param, levels = c('TDS', 'Cond',
'Mg', 'Ca', 'Cl', 'Na', 'SO4')) sampdate = as.Date(sampdate)})
Error: unexpected symbol in "tds.a <- within(tds.anal, {param =
factor(param, levels = c('TDS', 'Cond', 'Mg', 'Ca', 'Cl', 'Na', 'SO4'))
sampdate"

   So I did the conversion and melting the long way:
> tds.a <- tds.anal
> tds.a$sampdate <- factor(tds.a$sampdate)

   Now sampdate is a factor, and quant has the proper values:
str(tds.a)
'data.frame':	11434 obs. of  4 variables:
  $ site    : Factor w/ 143 levels "BC-0.5","BC-1",..: 134 127 134 134 73 73
  $ sampdate: Factor w/ 890 levels "1981-11-30","1982-04-28",..: 686 268 727
  $ 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 ...

  However, ...

> dcast(tds.a, site + sampdate ~ param, value_var = 'quant')

c.tds.anal <- dcast(tds.a, site + sampdate ~ param, value_var = 'quant') 
Aggregation function missing: defaulting to length.

   That's because c.tds.anal has lost the quant values:

str(c.tds.anal)
'data.frame':	2309 obs. of  9 variables:
  $ site    : Factor w/ 143 levels "BC-0.5","BC-1",..: 1 1 1 2 2 2 2 2 2 2
...
  $ sampdate: Factor w/ 890 levels "1981-11-30","1982-04-28",..: 239 252 260
99 101 102 155 163 170 179 ...
  $ Ca      : int  1 0 0 1 1 1 1 1 0 1 ...
  $ Cl      : int  1 0 0 1 1 1 1 1 0 1 ...
  $ Cond    : int  1 1 1 1 1 1 1 1 1 1 ...
  $ Mg      : int  1 0 0 1 1 1 1 1 0 1 ...
  $ Na      : int  0 0 0 1 1 1 1 1 0 1 ...
  $ SO4     : int  1 1 1 1 1 1 1 1 0 1 ...
  $ TDS     : int  1 1 1 1 1 1 1 1 0 1 ...

   I don't see what I did differently from your sample code.

Rich



More information about the R-help mailing list