【问题标题】:rfind equivalent in R在 R 中找到等价物
【发布时间】:2017-06-28 00:31:36
【问题描述】:

我希望使用类似 python 的 rfind,但在 R 中。

基本上,我有一个这样的字符串:"Black-crowned Night-Heron - Nycticorax nycticorax",我正在寻找那个中间连字符(“-”)的索引。

最终目标是保存该索引值并使用 substr() 函数获取子字符串,最终结果只是通用名称:"Black-crowned Night-Heron"。

到目前为止,我有newvar = regexpr(" - ", specieslist, fixed = T),然后是substr(specieslist, 1, newvar),但它返回的是常用名称,它们后面有一个空格。

那么,我想成为什么样的人:"Black-crowned Night-Heron"

改为:"Black-crowned Night-Heron "

谢谢!

【问题讨论】:

  • substr(*, newvar - 1)
  • @HongOoi 谢谢,成功了!!
  • sub(" - ..*", "", input) -- 正则表达式为空格、减号、空格、点、星号。
  • 您甚至可以使用sub("\\s+-\\s+.+$", "", txt) 来计算破折号两侧的任意数量的空格。
  • 最终目标strsplit(x, " - ")?

标签: r indexing


【解决方案1】:

不确定内置函数,但这似乎可行:

> str.rfind <- function(s, char) { rev(grep(char, unlist(strsplit(s, NULL)), fixed=T))[1]}
> str.rfind('This is nice.', 's')
  [1] 7
> str.rfind('This is nice.', '@')
  [1] NA

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多