user11425977
user11425977

Reputation:

How to check the position of similar elements in a vector

I have a vector like this:

firstChar=c("a","b","c","b","b","d","c")

I need to know the position of the similar element in vector, for example some thing like [2,4,5] and [3,7]. What function can do it simply.

Upvotes: 0

Views: 52

Answers (2)

user2974951
user2974951

Reputation: 10375

For every unique value

> for (i in unique(firstChar)) {
>   cat(i,which(firstChar==i),"\n")
> }

a 1 
b 2 4 5 
c 3 7 
d 6

Upvotes: 1

Aidan
Aidan

Reputation: 32

You can use the base function which for this:

which(firstChar == "a")
> [1] 1

which(firstChar == "b")
> [1] 2 4 5

which(firstChar == "c")
> [1] 3 7

Upvotes: 0

Related Questions