delete elements from list by rule
delete elements from list by rule
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.
2 Answers
2
You can do this by first Sort
ing 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.
Sort
First
DeleteDuplicatesBy
DeleteDuplicatesBy[Reverse@SortBy[lis, First], #[[2, 3]] &]
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.
DeleteDuplicatesBy
Thanks for contributing an answer to Mathematica Stack Exchange!
But avoid …
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Beaten to the punch :) Useful to note
DeleteDuplicatesBy
though!– Carl Lange
Sep 2 at 23:35