4
$\begingroup$

I have a list of dates, strings and integers:

lis = {{DateObject[{2000,1,1}],"a",1,"w"},{DateObject[{1999,12,31}],"a",1,"x"},{DateObject[{1999,12,31}],"a",2,"z"}

I would like to identify pairs of elements of lis that have identical values in their 2nd and 3rd position (in this case, "a" and 1), and then delete the older element of the pair, to leave:

res = {{DateObject[{2000,1,1}],"a",1,"w"},{DateObject[{1999,12,31}],"a",2,"z"}}

I realize this is likely be a duplicate question, but can't seem to find it; thanks for any thoughts.

$\endgroup$

2 Answers 2

4
$\begingroup$

You can do this by first Sorting the list by the date (the First element), reversing the order (so that we have newer first), then using DeleteDuplicatesBy to indicate the second and third column.

DeleteDuplicatesBy[Reverse@SortBy[lis, First], #[[{2, 3}]] &]
$\endgroup$
3
$\begingroup$

Would something like this work for you?

Last[SortBy[#, First]] & /@ GatherBy[lis, #[[{2, 3}]] &]

First, we gather by the 2nd and 3rd element and then, we grab the most recent element from each sublist by sorting them by date.

$\endgroup$
1
  • $\begingroup$ Beaten to the punch :) Useful to note DeleteDuplicatesBy though! $\endgroup$
    – Carl Lange
    Sep 2, 2018 at 23:35

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.