0
$\begingroup$

I have the following sample data:

test={{{2020, 1, 1}, 1}, {{2020, 1, 2}, 1}, {{2020, 1, 1}, 2}, {{2020, 2, 1}, 2}, {{2020, 1, 1}, 3},{{2019, 1, 1}, 1}}                      

I would like to first group the data by month and year, and then count how many entries are in each group (1, 2, or 3).

I would like the output to look something like this to then create a separate dataset:

<|{{2020, 1},1} -> 2, {{2020, 1},2} -> 1, {{2020, 2},2} ->1,{{2020, 1},3} -> 1,{{2019, 1},1} -> 1|>

I have tried a couple of things based on other questions asked, but I have not managed to figure it out. Any help would be greatly appreciated.

$\endgroup$
2
  • $\begingroup$ Is there any way of combining that so that the output would be something like this?: <|{{2020, 1},1} -> 2, {{2020, 1},2} -> 1, {{2020, 2},2} ->1,{{2020, 1},3} -> 1|> $\endgroup$ Oct 30, 2021 at 11:11
  • $\begingroup$ Did you look at CountsBy? $\endgroup$
    – Lukas Lang
    Oct 30, 2021 at 11:48

1 Answer 1

2
$\begingroup$
Clear["Global`*"]

$Version

(* "12.3.1 for Mac OS X x86 (64-bit) (June 19, 2021)" *)

test = {{{2020, 1, 1}, 1}, {{2020, 1, 2}, 1}, {{2020, 1, 1}, 
    2}, {{2020, 2, 1}, 2}, {{2020, 1, 1}, 3}, {{2019, 1, 1}, 1}};

assoc1 = CountsBy[test, {Most[#[[1]]], #[[2]]} &]

(* <|{{2020, 1}, 1} -> 2, {{2020, 1}, 2} -> 1, {{2020, 2}, 2} -> 
  1, {{2020, 1}, 3} -> 1, {{2019, 1}, 1} -> 1|> *)

ds1 = Dataset@assoc1

enter image description here

Alternatively,

assoc2 = CountsBy[test, {DateObject[#[[1]], "Month"], #[[2]]} &]

enter image description here

ds2 = Dataset@assoc2

enter image description here

$\endgroup$
2
  • $\begingroup$ As someone new to Mathematica, with the way the output is done, would it be possible to organize it into a timeseries? Or would I need to get rid of the association? $\endgroup$ Oct 30, 2021 at 13:21
  • $\begingroup$ Post a question showing an example of the intended input and the desired form of the output. $\endgroup$
    – Bob Hanlon
    Oct 30, 2021 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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