【问题标题】:How to replace all tags with respective variables in R?如何用R中的相应变量替换所有标签?
【发布时间】:2013-12-02 08:33:47
【问题描述】:

我有一个模板类型:

template <- "Average: {{av}} \n Sum: {{sum}}"
inputs <- list(av = "15", sum = "100")

我需要将所有出现的{{av}}{{sum}} 替换为inputs 的相应元素。

我试过了:

gsub("\\{\\{(.+)\\}\\}", inputs["\\1"], template, perl = TRUE)

但它会将所有标签替换为“NULL”。

如何正确更换?

【问题讨论】:

    标签: r parsing templates tags


    【解决方案1】:

    上一个解决方案的替代方案:

    for (i in names(inputs))
      regmatches(template,gregexpr(sprintf("\\{\\{%s\\}\\}", i), template)) <- inputs[[i]]
    

    HTH

    【讨论】:

    • 非常好。我怎样才能让它也代替大括号?
    • 我试过这个:regmatches(template,regexpr(sprintf("\{\{%s\}\}", i), template)) &lt;- inputs[[i]],但似乎没有产生理想的结果。
    • 非常感谢。我注意到它只替换了第一次出现的{{sum}}。是否可以替换所有出现的地方?
    • 是的,您只需将 regexpr 替换为现在编辑的 gregexpr
    【解决方案2】:

    您可以使用循环来完成。

    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}}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多