I have an unordered vector v
like the one shown below and would like to find the indices of the last occurrence of every unique elements in the list.
v <- scan(text="1 2 1 2 1 1 1 3 1 2 2 3 3 3 1 1 1 4 1 1 1 4 1 5 5 6
6 2 3 3 4 4 2 2 2 2 2 3 3 3 1 4 4 4 3 2 5 5 5 5")
v
# [1] 1 2 1 2 1 1 1 3 1 2 2 3 3 3 1 1 1 4 1 1 1 4 1 5 5 6 6 2 3 3 4 4 2 2 2 2 2 3 3 3
# [41] 1 4 4 4 3 2 5 5 5 5
Expected result (in order of 1, 2, 3, 4, 5):
41 46 45 44 50
I know I can use unique(unlist(v))
to find the unique elements but then how to find the indices of their last appearance? Any idea?
Thanks in advance.
Another approach that works even if the data are not ordered:
length(v1)-match(unique(v1),rev(v1))+1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With