[R] ReShape/cast question - sum of value in table

Ista Zahn istazahn at gmail.com
Sat Jul 11 15:46:56 CEST 2009


From: Mark Knecht <markknecht at gmail.com>
To: r-help <r-help at r-project.org>
Date: Fri, 10 Jul 2009 09:07:29 -0700
Subject: Re: [R] ReShape/cast question - sum of value in table
On Fri, Jul 10, 2009 at 8:38 AM, Mark Knecht<markknecht at gmail.com> wrote:
Hi Mark,
You can simplify the code a bit:

>
> <SNIP>
> >   What I need/want is that instead of displaying '1' or '2' - the
> > number of events that fit these EnTime/ExTime values - I need to have
> > the sum of the 'value' column from ReShape.Y.
> >
> >   Is this possible? I'm sure it's related the the Aggregation
> > requires fun.aggregate but cannot find an example of doing this sort
> > of thing, or don't recognize it when I'm looking at it.
> >
> > Thanks,
> > Mark
> >
> SOLVED
>
> It's so strange that after looking at this off and on for two days
> then I suddenly discover
>
> cast(ReShape.Y, EnTime ~ ExTime, function(x) sum(x))
>
all you really need is
cast(ReShape.Y, EnTime ~ ExTime, sum)
although I prefer
cast(ReShape.Y, EnTime ~ ExTime, fun.aggregate=sum)
for readability.

Also, you may want to look at the melt function in the reshape package
for the original conversion from the wide to the long form. Note that
the author of the reshape package has additional resources on his
website: http://had.co.nz/reshape/

-Ista

>
>
> which does what I need:
>
> > cast(ReShape.Y, EnTime ~ ExTime, function(x) sum(x))
>  EnTime   950  1125 1155 1210  1245  1305 1310
> 1     740     0     0    0    0     0     0 1760
> 2     750     0     0    0    0     0     0 -710
> 3     755 -1340     0    0    0     0     0 1650
> 4     800     0     0 -830    0     0     0  520
> 5     805     0     0    0    0     0     0 1080
> 6     810     0     0    0    0     0     0  -60
> 7     815     0     0    0    0     0     0  440
> 8     820     0     0    0    0     0     0 2150
> 9     850     0 -1120    0    0     0     0    0
> 10    855     0     0    0    0 -1040     0    0
> 11    925     0     0    0    0     0     0  680
> 12    935     0     0    0 -810     0     0    0
> 13    945     0     0    0    0     0     0 -340
> 14    950     0     0    0    0     0     0 -550
> 15   1125     0     0    0    0     0 -1420    0
> 16   1155     0     0    0    0     0     0  160
> 17   1210     0     0    0    0     0     0 1440
> 18   1245     0     0    0    0     0     0  110
> 19   1305     0     0    0    0     0     0  180
> >
>
> NOTE: There should have been a require(reshape) in the previous code
> for anyone trying to look at this later.
>
> Cheers,
> Mark




More information about the R-help mailing list