I have a nested list of numbers like { {36, -244}, {37, -225}, {38, -197}, {48, -200}, {49, -181}, {50, -133} } which needs to be further nested into "bins" according to a rule. I would describe the rule like: Elements belong into one bin when their first sub-elements (36, 37, 38 vs. 48, 49, 50) can form a chain of successive integers or in other words, if arranged from lowest to highest there is no "hole" greater than 1 in the so formed bins. In the following step, how can I tell Mathematica to average the second sub-elements (-244, -225...) inside the former defined bins?
$\begingroup$
$\endgroup$
l = {{36, -244}, {37, -225}, {38, -197}, {48, -200}, {49, -181}, {50, -133}};
l1 = Split[Sort @l, (#2[[1]] - #1[[1]] == 1 &)]
(*
{{{36, -244}, {37, -225}, {38, -197}},
{{48, -200}, {49, -181}, {50, -133}}}
*)
The second step
N /@ Mean /@ l1[[All, All, 2]]
(*{-222., -171.333}*)
Edit
For the larger dataset in your comment:
Graphics[{PointSize[Large], Pink, {Point@#, Green, Line@#} &@(Mean /@ l1),
Blue, Line /@ l1}, Axes -> True]
-
$\begingroup$ Thank you also! That code grouped even a larger dataset into correct bins. However, the second step yields results, but also one error per mean sounding like "Mean::rectt : Rectangular array expected at position 1 in Mean [..." Is this related to the [All,All,2]? $\endgroup$ – R.S. Apr 2 '13 at 18:57
-
$\begingroup$ Ok I got rid of the error by changing your code for the averaging to Mean /@l1[[All,All,2]]. Thanks that will save me days! $\endgroup$ – R.S. Apr 2 '13 at 19:17
-
$\begingroup$ @R.S. Oh, yep, sorry. I already found it but forgot to edit. Doing that now $\endgroup$ – Dr. belisarius Apr 2 '13 at 19:19
-
FindClusters[{{36, -244}, {37, -225}, {38, -197}, {48, -200}, {49, -181}, {50, -133}}, DistanceFunction -> (Abs[#1[[1]] - #2[[1]]] &)]
? $\endgroup$ – J. M.'s ennui♦ Apr 2 '13 at 18:15