0
$\begingroup$

I have the following sample data:

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

I would like to first group the data by month and year, and then count how many entries are in each group.

I would like the output to look something like this:

<|{{2020, 1},4}, {{2020, 2},1},{{2019, 1},1}|>
$\endgroup$

1 Answer 1

1
$\begingroup$

You can use CountsBy for this:

CountsBy[test[[All, 1]], d |-> d[[;; 2]]]

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

$\endgroup$
2
  • $\begingroup$ Is there a way to not make it an association? $\endgroup$ Commented Nov 1, 2021 at 10:03
  • $\begingroup$ You can use Normal on the association to transform it into a list of rules, or you can use Tally: Tally[test[[All, 1]], {d1, d2} |-> d1[[;; 2]] == d2[[;; 2]]] $\endgroup$
    – Carl Lange
    Commented Nov 1, 2021 at 10:26

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.