2
$\begingroup$

I'm new to Mathematica so please bare with me!

I wish to split an imported data list off of {x,y} values based off the y value, and then sum the corresponding parts.

An example of the imported list:

MyDataList = {{{20, "a"}, {3, "a"}, {4,"a"}, {6, "b"}, {10, "a"}, {12, "b"}, {2, "a"}}}

I want to make 2 sublists e.g.:

AList = {{20, "a"}, {3, "a"}, {4,"a"},{10, "a"},{2, "a"}}
BList = {{6,"b"},{12,"b"}}

And then sum the numerical parts of the list, e.g.:

AList = 39
Blist = 18

I've tried GatherBy and SplitBy to try and partition but it doesn't quite split how I need. Any advice would be super helpful!

$\endgroup$
0

3 Answers 3

6
$\begingroup$

You can use GroupBy. Note GroupBy returns an Association.

With

myDataList = {{{20, "a"}, {3, "a"}, {4, "a"}, {6, "b"}, {10, "a"}, {12, "b"}, {2, "a"}}};

Then

res = GroupBy[First@myDataList, Last -> First, Total]
<|"a" -> 39, "b" -> 18|>

and

res["a"]
39

Hope this helps.

$\endgroup$
5
$\begingroup$

Your list is wrapped in another list, so you can use First to remove the outer list.

{AList, BList} = GatherBy[First@MyDataList, Last];

Total[First /@ AList]
(* 39 *)

Total[First /@ BList]
(* 18 *)
$\endgroup$
2
  • $\begingroup$ Hi, when I try that it returns, Lists {Alist,Blist} and {MyDataList} are not the same shape? $\endgroup$
    – Schaef
    Mar 20, 2023 at 20:52
  • $\begingroup$ Then you must have changed something in your code. I used exactly the same MyDataList as you provided in the question, and it should work. $\endgroup$
    – Domen
    Mar 20, 2023 at 21:24
1
$\begingroup$

Using Reap/Sow:

Last@Reap@Scan[Sow[First@#, Last@#] &, MyDataList, {2}] // Map[Total]

Using Merge:

Rule @@@ (Reverse /@ First@MyDataList) // Merge[#, Total] & // Values

Result:

{39, 18}

$\endgroup$

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