r - 访问 gregexpr 的结果
问题描述
我想使用 gregexpr 函数来查找字符串中子字符串的开始和结束位置。该函数在控制台中运行良好,但我无法访问起始位置或字符串长度的结果:
g <- gregexpr("e", "cheese")
g
[[1]]
[1] 3 4 6
attr(,"match.length")
[1] 1 1 1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
g[[1]][1]
仅显示第一个值 (3),但我需要创建一个向量,其中包含起始位置和长度的所有值。谢谢。
解决方案
您可以通过这种方式提取它们:
g <- gregexpr("e", "cheese")
# one liner for : starts <- g[[1]]
# attributes(starts) <- NULL
starts <- `attributes<-`(g[[1]],NULL)
lens <- attr(g[[1]],'match.length')
> starts
[1] 3 4 6
> lens
[1] 1 1 1
当然,这仅适用于文本长度为 1 的情况(如示例中所示,因为它仅包含"cheese"
)。否则,您将需要遍历g
using g[[2]]
,g[[3]]
...等的元素。
推荐阅读
- ruby-on-rails - 响应未转换为 JSON
- nginx - Docker 私有注册表 /v2/_catalog 不提取 repos 但 /v2/repo/tags/ 有效?
- xpages - How to get HTML content out of Richtext field of Notesdocument
- webpack - Webpack 脚本加载器无法在 Chrome 中调试源代码
- java - 下载和显示图像的问题
- c# - 如何使用随机函数让我的矩形在不同的地方生成?
- r - 在ggplot小提琴图中为组着色
- reactjs - React 异步动作调度
- r - 在 R 中检查数据框中的值
- excel - CONCATENATE 和 IF 函数问题