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

你可能感兴趣的:(R语言字符串替换:gsub())