是否有R等价的python的字符串`format`函数?

时间:2017-06-26 15:21:22

标签: r replace

在python中有一个很好的函数(str .format),它可以很容易地用字符串中的变量(编码为{variable})替换存储在dict中的值(使用变量名称命名的值)。像这样:

vars=dict(animal="shark", verb="ate", noun="fish")
string="Sammy the {animal} {verb} a {noun}."
print(string.format(**vars)) 
  鲨鱼萨米吃了一条鱼。

R中最简单的解决方案是什么?是否有一个内置的等效2参数函数,它接受一个字符串,其变量编码为 方式并用名为list的命名值替换它们?

如果R中没有内置函数,是否在已发布的包中有一个?

如果已发布的软件包中没有,您会用什么来编写一个?

规则:使用编码为“{variable}”的变量为您提供字符串。变量必须编码为list。我会回答我的定制版本,但会接受一个比我更好的答案。

5 个答案:

答案 0 :(得分:15)

我找到了另一个解决方案:来自tidyverse的胶水包装: https://github.com/tidyverse/glue

一个例子:

library(glue)
animal <- "shark"
verb <- "ate"
noun <- "fish"
string="Sammy the {animal} {verb} a {noun}."
glue(string)
Sammy the shark ate a fish.

如果你坚持要有变量列表,你可以这样做:

l <- list(animal = "shark", verb = "ate", noun = "fish")
do.call(glue, c(string , l))
Sammy the shark ate a fish.

此致

帕维尔

答案 1 :(得分:3)

此功能可将{}转换为<%=%>,然后使用brew包中的brew你需要安装):

form = function(s,...){
 s = gsub("\\}", "%>", gsub("\\{","<%=",s))
 e = as.environment(list(...))
 parent.env(e)=.GlobalEnv
 brew(text=s, envir=e)
}

试验:

> form("Sammy the {animal} {verb} a {noun}.", animal = "shark", verb="made", noun="car")
Sammy the shark made a car.
> form("Sammy the {animal} {verb} a {noun}.", animal = "shark", verb="made", noun="truck")
Sammy the shark made a truck.

如果格式字符串中的任何{未标记变量替换,或者其中包含<%=或任何其他brew语法标记,则会失败。

答案 2 :(得分:2)

由于看起来我找不到内置的甚至是具有这种功能的包,我试图自己滚动。我的功能依赖于stringi包。以下是我的想法:

strformat = function(str, vals) {
    vars = stringi::stri_match_all(str, regex = "\\{.*?\\}", vectorize_all = FALSE)[[1]][,1]
    x = str
    for (i in seq_along(names(vals))) {
        varName = names(vals)[i]
        varCode = paste0("{", varName, "}")
        x = stringi::stri_replace_all_fixed(x, varCode, vals[[varName]], vectorize_all = TRUE)
    }
    return(x)
}

示例:

> str = "Sammy the {animal} {verb} a {noun}."
> vals = list(animal="shark", verb="ate", noun="fish")

> strformat(str, vals)
[1] "Sammy the shark ate a fish."

答案 3 :(得分:2)

stringr几乎在函数str_interp中有一个确切的替换。它只需要一点调整:

fmt = function(str, vals) {
    # str_interp requires variables encoded like ${var}, so we substitute
    # the {var} syntax here.
    x = stringr::str_replace_all(x, "\\{", "${")
    stringr::str_interp(x, args)
}

答案 4 :(得分:1)

library(glue)

list2env(list(animal="shark", verb="ate", noun="fish"),.GlobalEnv)
string="Sammy the {animal} {verb} a {noun}."
glue(string)

Sammy the shark ate a fish.