R 根据位置替换字符串中的符号

R 根据位置替换字符串中的符号,r,string,R,String,在下面的三个字符串中,我想用一个符号替换字符串中的最后一个符号,另一个保持不变。如何指定仅替换最后一个 在: 输出: 使用stri\u replace\u last\u fixed可以简化此过程 string <- 'd__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus|argenteus' stringi::stri

在下面的三个字符串中,我想用一个
符号替换字符串中的最后一个
符号,另一个保持不变。如何指定仅替换最后一个

在:

输出:


使用
stri\u replace\u last\u fixed
可以简化此过程

string <- 'd__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus|argenteus'
stringi::stri_replace_last_fixed(string, "|", "_")

#[1] "d__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus_argenteus"

string这是一个带有
gsub
和反向参考的
R base
解决方案:

gsub("\\|(\\w+$)", "_\\1", string)
[1] "d__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus_argenteus"
string <- 'd__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus|argenteus'
stringi::stri_replace_last_fixed(string, "|", "_")

#[1] "d__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus_argenteus"
gsub("\\|(\\w+$)", "_\\1", string)
[1] "d__Bacteria|p__Firmicutes|c__Bacilli|o__Staphylococcales|f__Staphylococcaceae|g__Staphylococcus|s__Staphylococcus_argenteus"