Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the indices of last occurrence of the unique elements in a vector

Tags:

r

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.

like image 859
Joarder Kamal Avatar asked Jan 06 '15 15:01

Joarder Kamal


1 Answers

Another approach that works even if the data are not ordered:

length(v1)-match(unique(v1),rev(v1))+1
like image 187
nicola Avatar answered Oct 25 '22 11:10

nicola