矢量元素的映射索引

时间:2014-07-15 00:23:07

标签: r list

这可能是一个微不足道的问题。

给出一个字符向量,其中一些是重复的:

vec <- c("a","b","d","e","e","f","g","a","d")

我正在寻找一个高效函数,该函数将为vec中每个唯一元素返回它在vec中出现的位置的索引。

我认为返回值就像这个列表:

list(a = c(1,8), b = 2, d = c(3,9), e = c(4,5), f = 6, g = 7)

1 个答案:

答案 0 :(得分:1)

以下是一些选择:

lapply(setNames(unique(vec),unique(vec)), function(x) which(x == vec) )
# or to avoid setNames and still ensure you get a list:
sapply(unique(vec), function(x) which(x == vec), simplify=FALSE)
# or even better but maybe not as extensible:
split(seq_along(vec),vec)

所有给予:

$a
[1] 1 8

$b
[1] 2

$d
[1] 3 9

$e
[1] 4 5

$f
[1] 6

$g
[1] 7