return indices of duplicated elements corresponding to the unique elements in R

↘锁芯ラ 提交于 2020-08-08 05:57:08

问题


anyone know if there's a build in function in R that can return indices of duplicated elements corresponding to the unique elements? For instance I have a vector a <- ["A","B","B","C","C"] unique(a) will give ["A","B","C"] duplicated(a) will give [F,F,T,F,T] is there a build-in function to get a vector of indices for the same length as original vector a, that shows the location a's elements in the unique vecor (which is [1,2,2,3,3] in this example)?

i.e., something like the output variable "ic" in the matlab function "unique". (which is, if we let c = unique(a), then a = c(ic,:)). http://www.mathworks.com/help/matlab/ref/unique.html

Thank you!


回答1:


We can use match

match(a, unique(a))
#[1] 1 2 2 3 3

Or convert to factor and coerce to integer

as.integer(factor(a, levels = unique(a)))
#[1] 1 2 2 3 3

data

a <- c("A","B","B","C","C")



回答2:


This should work:

cumsum( !duplicated( sort( a)) )  # one you replace  Mathlab syntax with R syntax.

Or just:

as.numeric(factor(a) )


来源:https://stackoverflow.com/questions/37495559/return-indices-of-duplicated-elements-corresponding-to-the-unique-elements-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!