我有一个字符串:
str1 <- "This is a string, that I've written
to ask about a question, or at least tried to."
Run Code Online (Sandbox Code Playgroud)
我怎么会:
1)计算逗号的数量
2)计算'-ion'的出现次数
有什么建议?
Jus*_*tin 21
该stringr
软件包具有str_count
很好地为您完成此功能的功能.
library(stringr)
str_count(str1, ',')
[1] 2
str_count(str1, 'ion')
[1] 1
Run Code Online (Sandbox Code Playgroud)
编辑:
因为我很好奇:
vec <- paste(sample(letters, 1e6, replace=T), collapse=' ')
system.time(str_count(vec, 'a'))
user system elapsed
0.052 0.000 0.054
system.time(length(gregexpr('a', vec, fixed=T)[[1]]))
user system elapsed
2.124 0.016 2.146
system.time(length(gregexpr('a', vec, fixed=F)[[1]]))
user system elapsed
0.052 0.000 0.052
Run Code Online (Sandbox Code Playgroud)
数学文本的一般问题需要正则表达式.在这种情况下,您只想匹配特定字符,但要调用的函数是相同的.你想要的gregexpr
.
matched_commas <- gregexpr(",", str1, fixed = TRUE)
n_commas <- length(matched_commas[[1]])
matched_ion <- gregexpr("ion", str1, fixed = TRUE)
n_ion <- length(matched_ion[[1]])
Run Code Online (Sandbox Code Playgroud)
如果你只想在单词的末尾匹配"离子",那么你需要正则表达式.\b
代表一个单词边界,你需要逃避反斜杠.
gregexpr(
"ion\\b",
"ionisation should only be matched at the end of the word",
perl = TRUE
)
Run Code Online (Sandbox Code Playgroud)