zl程序教程

您现在的位置是:首页 >  其它

当前栏目

R中的替换函数gsub

函数 替换
2023-06-13 09:13:02 时间

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---"

下面我们来举一个临床数据处理的例子

我们先读入临床数据
#读取临床数据
clin=read.table("clinical.tsv",header=T,sep="\t",quote="")
#去除重复的行
index=!duplicated(clin$case_submitter_id)
#提取非重复的样本的临床信息
clin=clin[index,]
可以得到如下临床信息表

前面给大家讲过☞肿瘤TNM分期,我们知道组织病理分期分成stage I,stage II,stage III和stage IV四个分期

接下来我们试着把组织病理分期从四个组合并成两个组,并转换成因子 我们使用gsub函数 #删除组织病理学分期末尾的A,B或者C等字母,例如Stage IIIA,Stage IIIB stage=gsub("[ABCD]$","",clin$ajcc_pathologic_stage) #将Stage III和Stage IV替换成stage III/IV stage=gsub("Stage IV.*","stage III/IV",stage) stage=gsub("Stage III.*","stage III/IV",stage) #将剩下的Stage I和Stage II替换成stage I/II stage=gsub("Stage.*","stage I/II",stage) #转换成因子 stage=factor(stage) stage 可以得到下面这个两分组的因子

接下来我们试着把组织病理分期从四个组合并成三个组,并转换成因子 我们还是使用gsub函数 #删除组织病理学分期末尾的A,B或者C等字母,例如Stage IIIA,Stage IIIB stage=gsub("[ABCD]$","",clin$ajcc_pathologic_stage) #将Stage III和Stage IV替换成stage III/IV,剩下的stageI和II保持不变 stage=gsub("Stage IV.*","stage III/IV",stage) stage=gsub("Stage III.*","stage III/IV",stage) #转换成因子 stage=factor(stage) stage 可以得到如下因子