[我发现使用R的"&"
"\&"
函数很难用base
替换gsub()
-
gsub("&", "\&", "A&B")
给出以下错误-
Error: '\&' is an unrecognized escape in character string starting ""\&"
有没有办法实现这种替代?
您可以使用
gsub("&", "\\&", "A&B",fixed=TRUE) # Fixed string replacement
gsub("(&)", "\\\\\\1", "A&B") # Regex replacement
结果仅包含一个反斜杠,您可以轻松地使用cat
或将内容保存到文本文件中进行检查:
cat(gsub("&", "\\&", "A&B",fixed=TRUE), collapse="\n")
cat(gsub("(&)", "\\\\\\1", "A&B"))