2010-03-16 74 views
1

我想要得到一個特定字母的索引,例如如何獲取列表A-Z中某個字母的索引?

> 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 

讓我知道這封信是存在的,但是我希望它在這種情況下返回6作爲列表的第6個元素。

回答

7

或者which

which(LETTERS=="G") 

which功能就是爲此而特別設計:

給出的邏輯 '真' 指數對象,允許數組索引。

which的函數也可以返回邏輯TRUE值的索引中通過設置arr.ind參數爲TRUE的矩陣(這是非常有用)。

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

你也可能需要閱讀this recent blog post from Seth Falcon,他談論了C.

4

嘗試grep

R> grep("G", LETTERS) 
[1] 7 
6

優化它只是爲了通知:我想你想match("G",LETTERS),讓你7。該解決方案在grepwhich
好處是,你可以使用它的字母的載體:

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 
相關問題