简体   繁体   English

R命令以增量替代

[英]R command for substitute in increments

I would like to replace below: 我想在下面替换:

[1] "annotated_SRR7059136_CD39-.txt" "annotated_SRR7059137_CD39+.txt"
[3] "annotated_SRR7059138_CD39-.txt" "annotated_SRR7059139_CD39+.txt"
[5] "annotated_SRR7059140_CD39-.txt" "annotated_SRR7059141_CD39+.txt"
[7] "annotated_SRR7059142_CD39-.txt" "annotated_SRR7059143_CD39+.txt"

into

[1] "1_CD39-.txt" "1_CD39+.txt"
[3] "2_CD39-.txt" "2_CD39+.txt"
[5] "3_CD39-.txt" "3_CD39+.txt"
[7] "4_CD39-.txt" "4_CD39+.txt"

So far, I've tried running this 到目前为止,我已经尝试运行此

x<- sub("annotated_SRR70591.*_","\\1",sampleFiles)

But I am getting 但是我越来越

[1] "CD39-.txt" "CD39+.txt" "CD39-.txt" "CD39+.txt" "CD39-.txt" "CD39+.txt"
[7] "CD39-.txt" "CD39+.txt"

instead of what I wanted. 而不是我想要的。 Any help would be much appreciated. 任何帮助将非常感激。 Thanks! 谢谢!

We can use rep and seq to generate the numbers and paste them together. 我们可以使用repseq生成数字并将其paste在一起。

paste0(rep(seq(length(sampleFiles)/2), each = 2), "_", 
           sub("annotated_SRR70591.*_","\\1",sampleFiles))

#[1] "1_CD39-.txt" "1_CD39+.txt" "2_CD39-.txt" "2_CD39+.txt" "3_CD39-.txt" 
#[6] "3_CD39+.txt" "4_CD39-.txt" "4_CD39+.txt"

For better understanding breaking down the steps, 为了更好地理解分解步骤,

rep(seq(length(sampleFiles)/2), each = 2) #gives
#[1] 1 1 2 2 3 3 4 4

and

sub("annotated_SRR70591.*_","\\1",sampleFiles) #gives
[1] "CD39-.txt" "CD39+.txt" "CD39-.txt" "CD39+.txt" "CD39-.txt" "CD39+.txt"
[7] "CD39-.txt" "CD39+.txt"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM