2017-04-10 137 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 
相关问题