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

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容