Re: How can I totalize by month, by year?
- To: mathgroup at smc.vnet.net
- Subject: [mg111909] Re: How can I totalize by month, by year?
- From: Ray Koopman <koopman at sfu.ca>
- Date: Wed, 18 Aug 2010 07:06:41 -0400 (EDT)
- References: <201006301204.IAA27569@smc.vnet.net> <i4d6av$6r3$1@smc.vnet.net>
On Aug 16, 10:22 pm, "Leandro Tenfen" <leandroten... at hotmail.com>
wrote:
> Hi,
>
> I'm new with Mathematica, I need some help to start it.
>
> I've got a date series like a cashflow, how can I totalize at each date
> change? And how can I totalize by month, by year, etc?
>
> For example:
>
> In[]=
>
> {{{{2010, 8, 3, 0, 0, 0.},
> 65.}, {{2010, 8, 3, 0, 0, 0.}, -72.}, {{2010, 8, 3, 0, 0, 0.},
> 45.}, {{2010, 8, 2, 0, 0, 0.}, 67.}, {{2010, 8, 2, 0, 0, 0.},
> 83.}, {{2010, 8, 2, 0, 0, 0.}, -42.}, {{2010, 7, 30, 0, 0,
> 0.}, -32.}, {{2010, 7, 30, 0, 0, 0.},
> 48.}, {{2010, 7, 30, 0, 0, 0.}, 12.}, {{2010, 7, 30, 0, 0, 0.},
> 34.}, {{2010, 7, 29, 0, 0, 0.}, -52.}, {{2010, 7, 29, 0, 0, 0.},
> 78.}, {{2010, 7, 29, 0, 0, 0.}, -26.}, {{2010, 7, 28, 0, 0, 0.},
> 45.}, {{2010, 7, 28, 0, 0, 0.}, -23.}, {{2010, 7, 28, 0, 0,
> 0.}, -32.}, {{2010, 7, 28, 0, 0, 0.},
> 74.}, {{2010, 7, 27, 0, 0, 0.}, 53.}, {{2010, 7, 27, 0, 0, 0.},
> 58.}, {{2010, 7, 27, 0, 0, 0.}, 25.}}}
>
> Out[]=
>
> {{{{2010, 8, 3, 0, 0, 0.}, 38.}, {{2010, 8, 2, 0, 0, 0.},
> 108.}, {{2010, 7, 30, 0, 0, 0.},
> 28.}, {{2010, 7, 29, 0, 0, 0.}, -10.}, {{2010, 7, 28, 0, 0, 0.},
> 64.}, {{2010, 7, 2, 0, 0, 0.}, 136.}}}
>
> Thanks
> Leandro Tenfen
data = Flatten[ (* eliminate the outer level *)
{{{{2010, 8, 3, 0, 0, 0.}, 65.},
{{2010, 8, 3, 0, 0, 0.}, -72.},
{{2010, 8, 3, 0, 0, 0.}, 45.},
{{2010, 8, 2, 0, 0, 0.}, 67.},
{{2010, 8, 2, 0, 0, 0.}, 83.},
{{2010, 8, 2, 0, 0, 0.}, -42.},
{{2010, 7, 30, 0, 0, 0.}, -32.},
{{2010, 7, 30, 0, 0, 0.}, 48.},
{{2010, 7, 30, 0, 0, 0.}, 12.},
{{2010, 7, 30, 0, 0, 0.}, 34.},
{{2010, 7, 29, 0, 0, 0.}, -52.},
{{2010, 7, 29, 0, 0, 0.}, 78.},
{{2010, 7, 29, 0, 0, 0.}, -26.},
{{2010, 7, 28, 0, 0, 0.}, 45.},
{{2010, 7, 28, 0, 0, 0.}, -23.},
{{2010, 7, 28, 0, 0, 0.}, -32.},
{{2010, 7, 28, 0, 0, 0.}, 74.},
{{2010, 7, 27, 0, 0, 0.}, 53.},
{{2010, 7, 27, 0, 0, 0.}, 58.},
{{2010, 7, 27, 0, 0, 0.}, 25.}}}, 1];
The difference between daily, monthly, and yearly
is in how many elements SplitBy uses to match on.
{#[[1,1]],Tr@#[[All,2]]}& /@ SplitBy[data,#[[1,{1,3}]]&] (* daily *)
{{{2010, 8, 3, 0, 0, 0.}, 38.},
{{2010, 8, 2, 0, 0, 0.}, 108.},
{{2010, 7, 30, 0, 0, 0.}, 62.},
{{2010, 7, 29, 0, 0, 0.}, 0.}, (* how did you get -10. here? *)
{{2010, 7, 28, 0, 0, 0.}, 64.},
{{2010, 7, 27, 0, 0, 0.}, 136.}}
{#[[1,1]],Tr@#[[All,2]]}& /@ SplitBy[data,#[[1,{1,2}]]&] (* monthly *)
{{{2010, 8, 3, 0, 0, 0.}, 146.},
{{2010, 7, 30, 0, 0, 0.}, 262.}}
{#[[1,1]],Tr@#[[All,2]]}& /@ SplitBy[data,#[[1,{1,1}]]&] (* yearly *)
{{{2010, 8, 3, 0, 0, 0.}, 408.}}