6
$\begingroup$

Consider data of a format such as

data = {{{2002, 7, 30}, 1.20431}, {{2002, 7, 31}, 0.52822}, 
        {{2002, 8, 1}, -1.51937}, {{2002, 8, 2}, -1.2966},
        {{2002, 8, 5}, -1.97334}, {{2002, 8, 6}, 1.07311},
        {{2002, 8, 7}, 0.224605}, {{2002, 8, 8}, 1.78266},
        {{2002, 8, 9}, 0.90241}, {{2002, 8, 12}, 0.502187}};

I'd like to have a function that adds a dimension to the list and automatically collects all data points belonging to a single week together, e.g.:

weekly[data]

with output

 {
  {
    {{2002, 7, 30}, 1.20431}, {{2002, 7, 31}, 0.52822}, 
    {{2002, 8, 1}, -1.51937}, {{2002, 8, 2}, -1.2966}
  }
  ,
  {
    {{2002, 8, 5}, -1.97334}, {{2002, 8, 6}, 1.07311},
    {{2002, 8, 7}, 0.224605}, {{2002, 8, 8}, 1.78266},
    {{2002, 8, 9}, 0.90241}
  }
  ,
  {
    {{2002, 8, 12}, 0.502187}
  }
 };

Is there a function in Mathematica that can do this? Or maybe one can implement it?

$\endgroup$
  • 1
    $\begingroup$ Convert to DateObject, sort, get the days of the week, split by whichever day you consider as starting your week (maybe Monday?), $\endgroup$ – b3m2a1 Aug 20 at 3:51
7
$\begingroup$

You can GatherBy using DateValue with "Week" ({"Year","Week"} if the input data spans multiple years) as date element as the second argument:

GatherBy[data, DateValue[#[[1]], "Week"] &]

{{{{2002, 7, 30}, 1.20431}, {{2002, 7, 31}, 0.52822}, {{2002, 8, 1}, -1.51937}, {{2002, 8, 2}, -1.2966}},
{{{2002, 8, 5}, -1.97334}, {{2002, 8, 6}, 1.07311}, {{2002, 8, 7}, 0.224605}, {{2002, 8, 8}, 1.78266}, {{2002, 8, 9}, 0.90241}},
{{{2002, 8, 12}, 0.502187}}}

$\endgroup$
3
$\begingroup$

Additionally, CurrentDate and PreviousDate work too. CurrentDate appears to be implemented in terms of PreviousDate. Of course, NextDate would also work.

GatherBy[data, CurrentDate[First[#], "Week"] &]

{{{{2002, 7, 30}, 1.20431}, {{2002, 7, 31}, 0.52822}, {{2002, 8, 1}, -1.51937}, {{2002, 8, 2}, -1.2966}}, {{{2002, 8, 5}, -1.97334}, {{2002, 8, 6}, 1.07311}, {{2002, 8, 7}, 0.224605}, {{2002, 8, 8}, 1.78266}, {{2002, 8, 9}, 0.90241}}, {{{2002, 8, 12}, 0.502187}}}

GatherBy[data, PreviousDate[First[#], "Week"] &]
$\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.