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

nsh*_*eff 12 replace r

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

vars=dict(animal="shark", verb="ate", noun="fish")
string="Sammy the {animal} {verb} a {noun}."
print(string.format(**vars)) 
Run Code Online (Sandbox Code Playgroud)

鲨鱼萨米吃了一条鱼.

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

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

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

规则:字符串由编码为"{variable}"的变量提供给您.变量必须编码为a list.我将回答我的定制版本,但会接受一个比我更好的答案.

Paw*_*ski 18

我找到了另一个解决方案:来自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.
Run Code Online (Sandbox Code Playgroud)

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

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

问候

帕维尔