[英]paste0 or paste fails when it encounters special characters in r
我有这个字符串。
temp <- "this is Mapof ttMapof qwqqwMApofRt it"
我必须将此作为输出。
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
我正在这样做:(完美,没问题!)
temp <- gsub('Mapof\\b', 'Mapof (Mapof)', temp) #code line 1
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
但是问题是我不能直接执行此操作,因为我必须从向量中获取“模式”和“替换”。 因此,从该向量中提取“模式”和“替换”后,我将其存储为以下内容
inc_spelling <- "Mapof" #(pattern)
cor_spelling <- "Map of" #(replacement)
现在,我按照以下方式使用paste()来获取确切的代码行1(上面),但是不会发生。 你自己看。 这是怎么了?
txt <- paste0("temp <- gsub('",inc_spelling,"\\b','",inc_spelling," (",cor_spelling,")'"," ,temp)")
txt
"temp <- gsub('Mapof\\b','Mapof (Map of)' ,temp)"
eval(parse(text=txt))
temp
"this is Mapof ttMapof qewqeqwMapofdffd it"
它失败! 为什么会这样呢? 我无法找出错误! 如果不能通过paste()完成此任务,请提出另一种选择。 谢谢!
您尝试过的解决方案要复杂得多。 您可以将向量参数直接提供给gsub()
:
gsub(paste0(inc_spelling, '\\b'), cor_spelling, temp)
还是这不是您要尝试的做法?
如果您想使用eval(parse())
(提示:您不要调整@MadScone的答案以适应您的需求),则需要更多的转义符(即,您需要对原先的转义符以及原始的转义。您知道这有多疯狂吗?应避免使用eval(parse())
):
txt <- paste0("temp <- gsub('",inc_spelling,"\\\\b','",
inc_spelling," (",
cor_spelling,")'"," ,temp)")
print(eval(parse(text=txt)))
#[1] "this is Mapof (Map of) ttMapof (Map of) qwqqwMApofRt it"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.