返回与R中唯一元素对应的重复元素的索引 [英] return indices of duplicated elements corresponding to the unique elements in R
问题描述
有人知道R中是否有一个内置函数可以返回对应于唯一元素的重复元素的索引吗? 例如我有一个向量 a<-["A","B","B","C","C"] unique(a)将给出["A","B","C"] 重复的(a)将给出[F,F,T,F,T] 是否有一个内置函数来获取与原始向量a相同长度的索引向量,该函数显示a的元素在唯一vecor中的位置(在此示例中为[1,2,2,3,3]) ?
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)?
,例如,类似于matlab函数"unique"中的输出变量"ic". (也就是说,如果让c = unique(a),则a = c(ic,:)). http://www.mathworks.com/help/matlab/ref/unique.html
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
谢谢!
推荐答案
我们可以使用match
match(a, unique(a))
#[1] 1 2 2 3 3
或转换为factor
并强制转换为integer
Or convert to factor
and coerce to integer
as.integer(factor(a, levels = unique(a)))
#[1] 1 2 2 3 3
数据
a <- c("A","B","B","C","C")
这篇关于返回与R中唯一元素对应的重复元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!