我有一个以下类型的模板:
template <- "Average: {{av}} \n Sum: {{sum}}"
inputs <- list(av = "15", sum = "100")我需要将所有出现的{{av}}和{{sum}}替换为inputs的相应元素。
我试过了:
gsub("\\{\\{(.+)\\}\\}", inputs["\\1"], template, perl = TRUE)但是它用"NULL“替换了所有的标签。
我如何才能正确地进行更换?
发布于 2013-12-02 16:51:54
前一种解决方案的替代方案:
for (i in names(inputs))
regmatches(template,gregexpr(sprintf("\\{\\{%s\\}\\}", i), template)) <- inputs[[i]]HTH
发布于 2013-12-02 16:43:00
你可以使用一个循环来完成。
template <- "Average: {{av}} \n Sum: {{sum}}"
inputs <- list(av = "15", sum = "100")
template.copy <- template
for (i in 1:length(inputs)) {
x <- inputs[i]
xn <- names(x)
template.copy <- gsub(paste("\\{\\{", xn ,"\\}\\}", sep = ""),
paste("\\{\\{", x, "\\}\\}", sep = ""),
x = template.copy, perl = TRUE)
}
> template.copy
[1] "Average: {{15}} \n Sum: {{100}}"https://stackoverflow.com/questions/20323860
复制相似问题