'How to split character strings into two groups based on logically comparing their first two and last 4 characters?

I am rather new here. First of all many thanks for all the expert help one can find here! I have a very specific problem that I could not find a solution for so I am posting it. If I can clarify better, please let me know.

I have several character vectors which identify cabinets in specific countries and years:

cases <- c("AU1999,AU2002,AU2005,FI1960,FI1962,FI1964,KR1988,KR1993", "DE2006", 
           "AU1974,AU1983,AU1985,AU1990,AU1992,DE1977,FI1995,GB1975,GB1976") 

here is the output:

> cases
[1] "AU1999,AU2002,AU2005,FI1960,FI1962,FI1964,KR1988,KR1993"       
[2] "DE2006"                                                        
[3] "AU1974,AU1983,AU1985,AU1990,AU1992,DE1977,FI1995,GB1975,GB1976"

Now, for each vector I want to keep only a subset of it. Namely, if in the same vector for the same country (e.g. AU) there are several years, I want to keep the last year only, e.g. AU2005 in [1].

Thus, the output I want to generate would be cases I want to keep and cases I want to delete:

> keepcases
[1] "AU2005" "FI1964" "KR1993" "DE2006" "AU1992" "DE1977" "FI1995" "GB1976"

> deletecases
[1] "AU1999" " AU2002" "FI1960" "FI1962" "KR1988" "AU1974" "AU1983" "AU1985" "AU1990" "GB1975"

I appreciate your help with this a lot.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source