4
$\begingroup$

Is there a way to write a function where the input is a vector and the output is the elements in the vector that are repeated?

I was trying to use something along the lines:

f[x_] := DeleteCases[Gather[x], Length[#1] != 1]

Of course this doesn't work, giving me this output:

input: f[{1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}] 
output: {{1, 1}, {2, 2, 2}, {4}, {3}, {5, 5}, {7}, {8}, {9}, {0}, {11}}

If I was able to delete the elements with Length 1, I could delete easily construct the output

$\endgroup$
1
  • 2
    $\begingroup$ Maybe f[x_] := Select[Gather[x], Length[#] != 1 &][[All, 1]]. $\endgroup$
    – JimB
    Apr 23, 2021 at 22:27

4 Answers 4

7
$\begingroup$

DeleteCases requires a pattern, not a function, as second argument:

f[x_] := DeleteCases[Gather[x], {_}]

f[{1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}]
(*    {{1, 1}, {2, 2, 2}, {5, 5}}    *)
$\endgroup$
5
$\begingroup$

You may use Tally and ConstantArray.

With

lst = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11}

and

repeatedElements[lst_List] := ConstantArray @@@ DeleteCases[Tally[lst], {_, 1}]

then

repeatedElements[lst]
{{1, 1}, {2, 2, 2}, {5, 5}}

Hope this helps.

$\endgroup$
4
$\begingroup$
list = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11};

Gather + Cases

ClearAll[duplicateElements1]
duplicateElements1 = Cases[{_, __}] @* Gather;

duplicateElements1 @ list
{{1, 1}, {2, 2, 2}, {5, 5}}

Counts + Select + KeyValueMap:

ClearAll[duplicateElements2]
duplicateElements2 = KeyValueMap[ConstantArray] @* Select[GreaterThan @ 1] @* Counts;

duplicateElements2 @ list
{{1, 1}, {2, 2, 2}, {5, 5}}

GroupBy + Values

ClearAll[duplicateElements3]
duplicateElements3 = Values @ GroupBy[#, Identity, If[Length@# > 1, #, Nothing] &] &;

duplicateElements3 @ list
{{1, 1}, {2, 2, 2}, {5, 5}}
$\endgroup$
2
$\begingroup$

You could use ResourceFunction["Duplicates"]

list = {1, 2, 2, 1, 4, 3, 5, 5, 2, 7, 8, 9, 0, 11};
Gather@ResourceFunction["Duplicates"]@list

(* result: {{1, 1}, {2, 2, 2}, {5, 5}} *)

And here's another way using undocumented function GeneralUtilities`FindDuplicates

With[{c = Counts@list},
 ConstantArray[#, c[#]] & /@ GeneralUtilities`FindDuplicates[list]
]
$\endgroup$

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.