美文网首页
R语言字符串替换:gsub()

R语言字符串替换:gsub()

作者: 蜘蛛鱼 | 来源:发表于2019-03-27 20:19 被阅读0次
    gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
        fixed = FALSE, useBytes = FALSE)
    

    其中pattern是要替换的字符,replacement是替换的字符,x是对应的string或string vector。

    举例如下:

    > x <- "R Tutorial"
    > gsub("ut","ot",x)
    [1] "R Totorial"
    

    ignore.case表示是否忽视大小写。

    举例vector:

    > x <- c("R Tutorial","PHP Tutorial", "HTML Tutorial")
    > gsub("Tutorial","Examples",x)
    [1] "R Examples"    "PHP Examples"  "HTML Examples"
    

    还有其他的一些例子来灵活使用这个函数,更详细的说明看下面的Ref就可以了。

    > x <- "line 4322: He is now 25 years old, and weights 130lbs"
    > y <- gsub("\\d+","---",x)
    > y
    [1] "line ---: He is now --- years old, and weights ---lbs"
     
    
    > x <- "line 4322: He is now 25 years old, and weights 130lbs"
    > y <- gsub("[[:lower:]]","-",x)
    > y
    [1] "---- 4322: H- -- --- 25 ----- ---, --- ------- 130---"
    

    Ref:
    http://www.endmemo.com/program/R/gsub.php

    相关文章

      网友评论

          本文标题:R语言字符串替换:gsub()

          本文链接:https://www.haomeiwen.com/subject/vwwtbqtx.html