获取R中字符串第一个大写字母的索引?
Get the index of the first uppercase letter of a string in R?
我正在尝试获取 R 中字符串第一个字符的索引。但是我搜索过的大部分答案都是用 grepl
检查整个字符串是否为大写。 Python 可以轻松做到这一点,但我还没有找到可以在 R 中做到这一点的库。
假设您从以下内容开始:
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
一种直接的方法是将每个字符串拆分为单个字母向量并测试大写字母:
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
我正在尝试获取 R 中字符串第一个字符的索引。但是我搜索过的大部分答案都是用 grepl
检查整个字符串是否为大写。 Python 可以轻松做到这一点,但我还没有找到可以在 R 中做到这一点的库。
假设您从以下内容开始:
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
一种直接的方法是将每个字符串拆分为单个字母向量并测试大写字母:
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