Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取R中字符串的第一个大写字母的索引?_R_String_Indexing_Uppercase - Fatal编程技术网

获取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]") ##

我试图获取R中字符串的第一个字符的索引。但我搜索的大多数答案都是用
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