【发布时间】:2014-06-23 12:01:22
【问题描述】:
我正在寻找一个基于 gsub 的函数,它可以让我进行组合字符串替换,这样如果我有任意数量的字符串替换规则
replrules=list("<x>"=c(3,5),"<ALK>"=c("hept","oct","non"),"<END>"=c("ane","ene"))
和一个目标字符串
string="<x>-methyl<ALK><END>"
它会给我一个数据框,其中包含最终的字符串名称和在
中所做的替换name x ALK END
3-methylheptane 3 hept ane
5-methylheptane 5 hept ane
3-methyloctane 3 oct ane
5-methyloctane 5 ... ...
3-methylnonane 3
5-methylnonane 5
3-methylheptene 3
5-methylheptene 5
3-methyloctene 3
5-methyloctene 5
3-methylnonene 3
5-methylnonene 5
目标字符串可以是任意结构,例如也可以是string="1-<ALK>anol",或者每个模式都可能出现多次,如string="<ALK>anedioic acid, di<ALK>yl ester"
在 R 中做这种事情最优雅的方式是什么?
【问题讨论】:
-
你怎么知道 x = 3 在第一行表示“hept”和“ane”?它们都井井有条吗?
-
顺序对我来说无关紧要 - 但我假设在这种情况下,首先循环遍历
中的 val,然后遍历 中的 val,然后遍历