我有这个字符串.
temp <- "this is Mapof ttMapof qwqqwMApofRt it"
Run Code Online (Sandbox Code Playgroud)
我必须把它作为输出.
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
Run Code Online (Sandbox Code Playgroud)
我这样做:(完美没问题!)
temp <- gsub('Mapof\\b', 'Mapof (Mapof)', temp) #code line 1
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
Run Code Online (Sandbox Code Playgroud)
但问题是我不能直接这样做,因为我必须从矢量中采取'模式'和'替换'.因此,在从该向量中提取"模式"和"替换"后,我将它们存储如下
inc_spelling <- "Mapof" #(pattern)
cor_spelling <- "Map of" #(replacement)
Run Code Online (Sandbox Code Playgroud)
现在我使用如下的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"
Run Code Online (Sandbox Code Playgroud)
它失败!为什么会这样?我无法找出错误!如果这个任务无法通过paste()实现,请提出另一种选择.谢谢!
您尝试过的解决方案需要更加复杂.您可以直接将矢量参数提供给gsub():
gsub(paste0(inc_spelling, '\\b'), cor_spelling, temp)
Run Code Online (Sandbox Code Playgroud)
或者这不是你想要做的?