加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 如何编辑R中的colnames?

发布时间:2020-12-13 21:53:12 所属栏目:百科 来源:网络整理
导读:我有名为name的变量,我想将它设置为我的矩阵的列名,但在此之前,我需要编辑名为name的变量中的名称 name[722] "TCGA-OL-A66N-01A-12R-A31S-13.isoform.quantification.txt"[723] "TCGA-OL-A66O-01A-11R-A31S-13.isoform.quantification.txt"[724] "TCGA-OL-A6
我有名为name的变量,我想将它设置为我的矩阵的列名,但在此之前,我需要编辑名为name的变量中的名称
>name
[722] "TCGA-OL-A66N-01A-12R-A31S-13.isoform.quantification.txt"
[723] "TCGA-OL-A66O-01A-11R-A31S-13.isoform.quantification.txt"
[724] "TCGA-OL-A66P-01A-11R-A31S-13.isoform.quantification.txt"

我想在第四个之前保留字母 –

预期产出:

>name
    [722] "TCGA-OL-A66N-01A"
    [723] "TCGA-OL-A66O-01A"
    [724] "TCGA-OL-A66P-01A"

有人会帮我在R中实现这个吗?

如果大小不同/不保证nchar,你可以使用stringr中的str_split_fixed().

stringr解决方案:

library(stringr)

name <- c(
    "TCGA-OL-A66N-01A-12R-A31S-13.isoform.quantification.txt","TCGA-OL-A66O-01A-11R-A31S-13.isoform.quantification.txt","TCGA-OL-A66P-01A-11R-A31S-13.isoform.quantification.txt")

apply(str_split_fixed(name,"-",5)[,1:4],1,paste0,collapse="-")

会给你什么:

## "TCGA-OL-A66N-01A" "TCGA-OL-A66O-01A" "TCGA-OL-A66P-01A"

说明:

> str_split_fixed(name,“ – ”,5)

根据前5个出版物将名称的每个向量元素分成5个部分 –

> [,1:4]

保留每个名称元素的前4个部分(结果矩阵的列)

> apply(…,collapse =“ – ”)

将它们粘贴在一起使用“ – ”折叠以恢复名称(按行)

但如果我有很多名字怎么办?

这里我将我的stringr apply()方法与@BondedDust grep方法和基本的strsplit方法进行比较.

首先,让我们将其提升到一万个名字:

name <- rep(name,3.334e3)

然后是一个微基准测试:

microbenchmark(
  stringr_apply = apply(str_split_fixed(name,collapse="-"),grep_ninja = sub("^([^-]*[-][^-]*[-][^-]*[-][^-]*)([-].*$)","1",name),strsplit = sapply( lapply( strsplit(name,"-"),"[",1:4),paste,times=25)

得到:

#  Unit: milliseconds
#  expr             min       lq    median        uq       max    neval
# stringr_apply 845.44542 874.5674 899.27849 941.22628 976.88903    25
# grep_ninja     25.51796  25.7066  25.85404  25.95922  27.89165    25
# strsplit      115.10626 123.2645 126.45171 130.10334 147.39517    25

似乎基本模式匹配/替换将更好地扩展…大约一秒钟或比最慢的方式快30倍.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读