【问题标题】:Replace character string elements by indices efficiently in R在R中有效地用索引替换字符串元素
【发布时间】:2014-07-01 12:32:39
【问题描述】:

我想有效地用特定位置的其他特定元素替换我的character 对象中的元素(这些位置是我知道的索引,因为它们是gregexpr 函数的结果)。

我想要一些 foo 函数,其工作原理如下:

foo("qwerty", c(1,3,5), c("z", "x", "y"))

给我:

[1] "zwxryy"

我搜索了 stringr 软件包 cran pdf,但没有任何想法。提前感谢您的任何建议。

【问题讨论】:

    标签: regex string r replace


    【解决方案1】:

    例如:

    xx <- unlist(strsplit("qwerty",""))
    xx[c(1,3,5)] <- c("z", "x", "y")
    paste0(xx,collapse='')
    [1] "zwxryy"
    

    【讨论】:

    • 好的,我看到你已经发布了,所以你可能应该将其修改为 foo &lt;- function(a,b,c){ temp &lt;- strsplit(a, "")[[1]]; temp[b] &lt;- c; paste0(temp, collapse = "") } 之类的内容以满足 OP 的要求
    【解决方案2】:

    如果你没有那么多字符要替换,你也可以试试下面的那个

      st1 <- "qwerty"
     gsub("^.(.).(.).","z\\1x\\2y", st1)
    #[1] "zwxryy"
    

    【讨论】:

      【解决方案3】:

      stringi 包中有stri_sub 函数,其工作原理如下:

      a <- "12345"
      stri_sub(a, from=c(1,3,5),len=1) <- letters[c(1,3,5)]
      a
      ## [1] "a2345" "12c45" "1234e"
      

      这几乎就是你想要的。只需在循环中使用它:

      a <- "12345"
      for(i in c(1,3,5)){
          stri_sub(a, from=i,len=1) <- letters[i] 
      }
      a
      ## [1] "a2c4e"
      

      请注意,此类功能在我们的 TODO 列表中,请检查: https://github.com/Rexamine/stringi/issues?state=open

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-08
        • 2017-05-28
        • 2021-03-03
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 2014-08-21
        • 2012-08-31
        相关资源
        最近更新 更多