r - 是否有 R 等效的 python 字符串 `format` 函数?

标签 r replace

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

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

Sammy the shark ate a fish.


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

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

如果发布的包中没有,你会用什么来写一个?

规则:给你的字符串带有编码为“{variable}”的变量。变量必须编码为 list .我会用我的定制版本来回答,但会接受比我做得更好的答案。

最佳答案

我找到了另一个解决方案:来自 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.

问候

帕维尔

关于r - 是否有 R 等效的 python 字符串 `format` 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763056/

相关文章:

javascript - 无法在 Javascript 中匹配此正则表达式

python - 将单引号替换为双引号 python pandas 数据框

html - 将导航栏放在标题底部

coding-style - 比较大写或小写是否更常见/标准?

r - 忽略未知的美学 : text in ggplot (using numbers or letters as points)

r - 将多行文本转换为数据框

r - 如何在RMarkdown中嵌入ggvis交互式图表?

javascript - jquery替换问题

r - renderImage 中的deleteFile = FALSE 不起作用

r - 在R中创建连续的热图