3
$\begingroup$

Given three arrays, for example

s={1,3,2,3,1,2,3,2,1}
r={4,2,6,5,4,6,2,1,3}
f={1,3,9,1,8,4,4,8,2}

I'm trying to output four summary arrays

  1. The uniques of s
  2. For each unique of s, the maximum of r with that s
  3. The number of entries which have that (s,r) combination
  4. The sum of f's of those corresponding entries

For example

o1={1,2,3}
o2={4,6,5}
o3={2,2,1}
o4={9,13,1}

(For s=1 the maximum r values was 4, of which there were two of them, and the sum of the corresponding f values is 1+8=9)

I've been doing a loop across the uniques using Position function, etc. Slow and not optimized using the Mathematica notation. The arrays can be millions in length.

Thank you for your help.

$\endgroup$

1 Answer 1

5
$\begingroup$
{o1, o2, o3, o4} = Transpose @  Values @ KeySort @
  GroupBy[Transpose[{s, r, f}], First, 
     Apply[{First @ #, First @ #2, Length @ #2, Total @ #3} &] @* 
       Transpose @* MaximalBy[#[[2]] &]]
{{1, 2, 3}, {4, 6, 5}, {2, 2, 1}, {9, 13, 1}}
$\endgroup$

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.