【问题标题】:How to extract a character from a string?如何从字符串中提取字符?
【发布时间】:2020-11-20 14:36:19
【问题描述】:

除了 substr 之外,还有其他函数可以只提取字符串的第 n 个元素吗?

str="abc"
str[3] #does not work when i want to extract c using index 3

【问题讨论】:

    标签: r string function


    【解决方案1】:

    stringr::str_sub

    library(stringr)
    str_sub(str, 3)
    [1] "c"
    

    【讨论】:

      【解决方案2】:

      这也有帮助:

      strsplit("abc",split='')[[1]][3]
      
      [1] "c"
      

      【讨论】:

      • 没有什么比方括号矢量更简单的了?如果是这样,那么 r 对于字符串是低效的...
      • @Isabelle 方法很多,最简单的就是substring()你说的!
      【解决方案3】:

      你可以试试下面的方法

      library(stringr)
      str="abc"
      extracion_string <- str_extract(str, regex("c"))
      #[1] "c"
      

      【讨论】:

        猜你喜欢
        • 2016-11-05
        • 2012-03-03
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        • 2012-10-24
        相关资源
        最近更新 更多