4
$\begingroup$

I need to sum values that belongs to same week. For example, I have the list x with one column and n rows. Format:

{{2007,1,3},0.2},{2007,1,4},0.1},{2007,1,5},0.14},{2007,1,8},0.}, ... {2014,10,17},-0.2},{2014,10,18},0.2},{2014,10,19},0.2}}.

Dates in list are sorted in the form from Oldest to Newest. Say differently, is there any function like function "Weekendum" in MS Excel that returns the number of week in the year, so i could use function „GatherBy“ that number of week and „Accumulate“ the values.

$\endgroup$
4
$\begingroup$

Using the function by Heike from Determining the week of a year from a given date which gives the week number from a date:

data = {{{2007, 1, 3}, 0.2}, {{2007, 1, 4}, 0.1}, {{2007, 1, 5}, 0.14}, 
       {{2007, 1, 8}, 0.}, {{2014, 10, 17}, -0.2}, {{2014, 10, 18},0.2}, 
       {{2014, 10, 19}, 0.2}};

(*replace date with week number for each entry*)
data2 = Table[{weekNumberUS[DateList[data[[i, 1]]]], data[[i, 2]]}, {i, Length[data]}];

(*make {week,sum}  matrix*)
{First[#[[1]]], Total[#[[All, 2]]]} & /@ SplitBy[data2, First]

(*  {{1, 0.44}, {2, 0.}, {42, 0.}, {43, 0.2}}  *)
$\endgroup$
1
$\begingroup$

Let's convert dates:

data ={
 {{2007, 1, 3},  0.2}, {{2007, 1, 4}, 0.1}, {{2007, 1, 5}, 0.14}, {{2007, 1, 8}, 0.}, 
 {{2014, 10, 17}, -0.2}, {{2014, 10, 18},  0.2}, {{2014, 10, 19}, 0.2}};

data = MapAt[DateList, data, {;; , 1}];

I don't know if this can be done automatically but unless I put there the very first day of the week with "neutral" value then Mathematica starts counting "Weeks" from the first data point. Kind of expected.

So let's add that day:

 PrependTo[data, {DateList[{2007, 1, 1}], 0}]
{{{2007, 1, 1, 0, 0, 0.}, 0}, {{2007, 1, 3, 0, 0, 0.}, 0.2}, 
   {{2007, 1, 4, 0, 0, 0.}, 0.1}, {{2007, 1, 5, 0, 0, 0.}, 0.14}, 
   {{2007, 1, 8, 0, 0, 0.}, 0.}, {{2014, 10, 17, 0, 0, 0.}, -0.2}, 
   {{2014, 10, 18, 0, 0, 0.}, 0.2}, {{2014, 10, 19, 0, 0, 0.}, 0.2}}

Now, in V10 you can do this automatically. We will get only 3 points because I use European week.

TimeSeriesAggregate[data, "Week", Total]

DateListPlot[{data, %}, Joined -> False]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.