2017-04-10 71 views

回答

4

做到這一點假設你開始喜歡的東西:

x <- c("stRing", "strIng", "String", "sTRIng", "string") 

你可以試試:

sapply(gregexpr("[A-Z]", x), `[`, 1) 
## [1] 3 4 1 2 -1 

另外還有 「stringi」 封裝,您可以使用:

library(stringi) 
stri_locate_first_regex(x, "[A-Z]") 
##  start end 
## [1,]  3 3 
## [2,]  4 4 
## [3,]  1 1 
## [4,]  2 2 
## [5,] NA NA 

正如評論所指出的@lmo,regexpr也適用,並消除了sapply需要:

regexpr("[A-Z]", x) 
## [1] 3 4 1 2 -1 
## attr(,"match.length") 
## [1] 1 1 1 1 -1 
## attr(,"useBytes") 
## [1] TRUE 
0

一個直接的方式將每個分割字符串轉換成燎信矢量和測試是在大寫字母:

x <- c("stRing", "strIng", "String", "string", "sTRIng") # from the other answer 

sapply(strsplit(x, ''), function(y) which(y %in% LETTERS)[1]) 

# [1] 3 4 1 NA 2 
相關問題