1
$\begingroup$

Consider the following table:

tabb = {{1, 2, 3, 4}, {5, 1, 7, 8}, {1, 2, 3, 4, 13, 16}, {5, 6, 7, 9}, {1, 2, 3, 4, 11, 16}, {5, 6, 7, 8}, {1, 2, 3, 4, 11, 16, 13, 35}, {1, 1, 3, 4, 11, 16, 13, 35}, {1, 1, 14, 8, 33, 8, 13, 35}};

Could you please tell me how to group it by the number of columns and also the product of each second column?

I.e., the rows {{1, 2, 3, 4}, {5, 1, 7, 8}, {5, 6, 7, 9},{5, 6, 7, 8}} of tabb have the same number of columns, but the products of the 2nd and 4th columns are different. Therefore, they should be considered as different elements: the first two rows form one element, while the remaining two form another two elements.

I probably should use GroupGy[tabb,{Length,condition}] where condition specifies the product of the columns. My problem is that I cannot generalize the condition to an arbitrary number of columns.

$\endgroup$

1 Answer 1

4
$\begingroup$

GroupBy takes as the second argument an arbitrary function which can serve as a "grouping parameter". As you have correctly identified it, you can use a list {length, product} as a parameter. To get every second element of a list, use Span.

GroupBy[tabb, {Length[#], Times @@ #[[2 ;; ;; 2]]} &]

(* <| {4, 8} -> {{1, 2, 3, 4}, {5, 1, 7, 8}}, 
      {6, 128} -> {{1, 2, 3, 4, 13, 16}, {1, 2, 3, 4, 11, 16}}, 
      {4, 54} -> {{5, 6, 7, 9}}, 
      {4, 48} -> {{5, 6, 7, 8}}, 
      {8, 4480} -> {{1, 2, 3, 4, 11, 16, 13, 35}}, 
      {8, 2240} -> {{1, 1, 3, 4, 11, 16, 13, 35}, {1, 1, 14, 8, 33, 8, 13, 35}}|> *)
$\endgroup$
3
  • $\begingroup$ Thanks! Could you please tell me what is the meaning of the symbols inside the bracket in #[[2 ;; ;; 2]]? $\endgroup$ May 29 at 13:41
  • 1
    $\begingroup$ It is a shorter syntax for Span, namely Span[2, All, 2] which means "start at the second element of the list, go through the whole list, taking every 2nd element". $\endgroup$
    – Domen
    May 29 at 13:46
  • 2
    $\begingroup$ Or, if you just want lists, use GatherBy instead of GroupBy $\endgroup$
    – Bob Hanlon
    May 29 at 13:57

Your Answer

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

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