4
$\begingroup$

I have a huge panel data. I want to create a new data keeping only first observation of each group. How can I achieve it? For illustrative purpose;

mydata = {{1, a, aa}, {1, b, bb}, {1, c, cc}, {2, d, dd}, {2, e, 
    ee}, {3, f, ff}, {3, g, gg}, {3, h, hh}, {4, i, ii}, {4, j, 
    jj}, {4, k, kk}, {4, l, ll}, {4, m, mm}, {5, n, nn}, {5, o, 
    oo}, {7, p, pp}};

My final result should be:

myanswer = {{1, a, aa}, {2, d, dd}, {3, f, ff}, {4, i, ii}, {5, n, 
    nn}, {7, p, pp}};

Any help is greatly appreciated.

$\endgroup$
5
$\begingroup$

This is a straightforward application of GatherBy and Map (/@):

First /@ GatherBy[mydata, First]

(* {{1, a, aa}, {2, d, dd}, {3, f, ff}, {4, i, ii}, {5, n, nn}, {7, p, pp}} *)

You could also use Part ([[]]) to get the first element of each group.

GatherBy[mydata, First][[All,1]]
$\endgroup$
  • 1
    $\begingroup$ Oops! Typing too fast – thanks bel! $\endgroup$ – Verbeia Nov 22 '14 at 4:55
  • $\begingroup$ @ Verbeia thank you for your answer. I did not know it was that simple. $\endgroup$ – ramesh Nov 22 '14 at 4:58
5
$\begingroup$
 First /@  Split[mydata, #1[[1]] == #2[[1]] &]
$\endgroup$
  • $\begingroup$ @ belisarius, thank you as always. Its that simple. $\endgroup$ – ramesh Nov 22 '14 at 4:57

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.