获取R中字符串的第一个大写字母的索引?
我试图获取R中字符串的第一个字符的索引。但我搜索的大多数答案都是用获取R中字符串的第一个大写字母的索引?,r,string,indexing,uppercase,R,String,Indexing,Uppercase,我试图获取R中字符串的第一个字符的索引。但我搜索的大多数答案都是用grepl检查整个字符串是否为大写。Python可以很容易地做到这一点,但我还没有找到在R中可以做到这一点的库。假设您从以下内容开始: x <- c("stRing", "strIng", "String", "sTRIng", "string") 还有“stringi”软件包,您可以使用该软件包: library(stringi) stri_locate_first_regex(x, "[A-Z]") ##
grepl
检查整个字符串是否为大写。Python可以很容易地做到这一点,但我还没有找到在R中可以做到这一点的库。假设您从以下内容开始:
x <- c("stRing", "strIng", "String", "sTRIng", "string")
还有“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
一种直接的方法是将每个字符串拆分为单字母向量,并测试大写字母:
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
x
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