我想使用 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
当然,这只适用于文本长度为 1 的情况(如示例中所示,因为它仅包含"cheese")。否则,您将需要迭代gusing g[[2]]、g[[3]]...等的元素。
| 归档时间: |
|
| 查看次数: |
2181 次 |
| 最近记录: |