user1701545
user1701545

Reputation: 6190

Mapping indices of vector elements

This is probably a trivial question.

Given a vector of characters, some of which are repeating:

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

I'm looking for an efficient function that will return for each unique element in vec the indices of where it appears in vec.

I imagine that the return value would be something like this list:

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

Upvotes: 1

Views: 48

Answers (1)

thelatemail
thelatemail

Reputation: 93813

Here's a few options:

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)

All giving:

$a
[1] 1 8

$b
[1] 2

$d
[1] 3 9

$e
[1] 4 5

$f
[1] 6

$g
[1] 7

Upvotes: 1

Related Questions