R替换函数gsub

时间:2022-07-22
本文章向大家介绍R替换函数gsub,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
    fixed = FALSE, useBytes = FALSE)

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

string举例如下:

> gsub("ut","ot",x)

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

vector举例如下:

> x <- c("R Tutorial","PHP Tutorial", "HTML Tutorial")
> gsub("Tutorial","Examples",x)
#将Tutorial替换成Examplers

[1] "R Examples"    "PHP Examples"  "HTML Examples"

还有其他的一些例子来灵活使用这个函数,结合正则表达式。

> x <- "line 4322: He is now 25 years old, and weights 130lbs"
> y <- gsub("\d+","---",x)
#\d表示一个任意的数字,+表示一个以上,所以4322和25都被替换成了---

> 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)
#[[:lower:]]匹配小写字母,将所有小写字母都替换成了-
> y
[1] "---- 4322: H- -- --- 25 ----- ---, --- ------- 130---"
转自:https://www.jianshu.com/p/7dfee5f1e884