1
$\begingroup$

Is it possible to find exact number of clusters with exact numbers of members in each cluster? Something like this:

data={1,2,1,1,3,2,2,3,2}

myClusters[data,{3,6}] -> {{1,1,1}, {2,2,2,2,3,3}}
myClusters[data,{2,4,3}] -> {{1,1}, {1,2,2,2}, {2,3,3}}

I guess the use of FindClusters, but any solution is possible (using Mathematica).

$\endgroup$
3
$\begingroup$
data = {1, 2, 1, 1, 3, 2, 2, 3, 2};

Internal`PartitionRagged[Sort @ data, {3, 6}]

{{1, 1, 1}, {2, 2, 2, 2, 3, 3}}

Internal`PartitionRagged[Sort @ data, {2, 4, 3}]

{{1, 1}, {1, 2, 2, 2}, {2, 3, 3}}

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Internal`PartitionRagged, that's what I was looking for!! $\endgroup$ – Quantum_Oli Oct 7 '16 at 14:44
  • $\begingroup$ Wow, an interesting package Internal! Thanks a lot $\endgroup$ – lesobrod Oct 7 '16 at 14:54
3
$\begingroup$

I'm a little uncertain as to exactly what you're asking for. Your 'clusters' are just sequential elements in your list.

Does this do what you want?

ListSplit[x_List, lengths_List] := 
  MapThread[Take[x, {##}] &, {Most[#], Rest[#] - 1}] &@Accumulate[Prepend[lengths, 1]]

Then simply:

ListSplit[Sort[data], {3, 6}]
ListSplit[Sort[data], {2,4,3}]

{{1, 1, 1}, {2, 2, 2, 2, 3, 3}}

{{1, 1}, {1, 2, 2, 2}, {2, 3, 3}}

| improve this answer | |
$\endgroup$
  • $\begingroup$ The ListSplit code is courtesy of @Leonid Shifrin. $\endgroup$ – Quantum_Oli Oct 7 '16 at 13:32
0
$\begingroup$
myClusters = FoldPairList[TakeDrop, Sort @ #, #2]&;

myClusters[data, {3, 6}]

{{1, 1, 1}, {2, 2, 2, 2, 3, 3}}

myClusters[data, {2, 4, 3}]

{{1, 1}, {1, 2, 2, 2}, {2, 3, 3}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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