tags:

views:

108

answers:

3

I want to get the index of a particular letter, e.g.

>  match(LETTERS,"G")
 [1] NA NA NA NA NA NA  1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Gives me that the letter exists, but I want it to return 6 in this case for the 6th element of the list.

+3  A: 

Try grep:

R> grep("G", LETTERS)
[1] 7
rcs
+6  A: 

Or which:

which(LETTERS=="G")

The which function is designed specifically for this purpose:

Give the 'TRUE' indices of a logical object, allowing for array indices.

The which function can also return the index for logical TRUE values in a matrix by setting the arr.ind argument to TRUE (this is very useful).

> which(matrix(LETTERS, nrow=5)=="G")
[1] 7
> which(matrix(LETTERS, nrow=5)=="G", arr.ind=TRUE)
     row col
[1,]   2   2

You may also want to read this recent blog post from Seth Falcon where he talks about optimizing it in C.

Shane
+4  A: 

Just for the notice: I think you wanted match("G",LETTERS) which gives you 7.
Benefits of this solution over grep or which is that you could use it on vector of letters:

match(c("S","T","A","C","K","O","V","E","R","F","L","O","W"), LETTERS)
# gives:
# [1] 19 20  1  3 11 15 22  5 18  6 12 15 23
Marek