19

有没有可以替代 paste 的功能?我想知道R中是否存在这样的东西:

> buildString ( "Hi {1}, Have a very nice {2} ! " , c("Tom", "day") )
4

5 回答 5

27

frankc 和 DWin 正确地指出了sprintf().

如果由于某种原因您的替换部件确实是向量的形式(即c("Tom", "day")),您可以使用do.call()将它们传递给sprintf()

string <- "Hi %s, Have a really nice %s!"
vals   <- c("Tom", "day")

do.call(sprintf, as.list(c(string, vals)))
# [1] "Hi Tom, Have a really nice day!"
于 2012-04-26T20:53:45.330 回答
21

sprintf功能是其他人提到的一种方法,这是使用该gsubfn包的另一种方法:

> library(gsubfn)
> who <- "Tom"
> time <- "day"
> fn$paste("Hi $who, have a nice $time")
[1] "Hi Tom, have a nice day"
于 2012-04-26T21:41:41.743 回答
19

我认为您正在寻找 sprintf。

具体来说:

sprintf("Hi %s, Have a very nice %s!","Tom","day")
于 2012-04-26T20:43:14.757 回答
17

whisker软件包在这方面做得很好,值得更广泛的赞赏:

require(whisker)
whisker.render ( "Hi {{name}}, Have a very nice {{noun}} ! " , list(name="Tom", noun="day") )
于 2012-04-27T01:30:22.373 回答
2

在 1.1.0 版本(CRAN 于 2016-08-19 发布)中,该stringr包获得了字符串插值功能str_interp()

可以使用str_interp()以下用例:

环境中定义的变量

v1 <- "Tom"
v2 <- "day"
stringr::str_interp("Hi ${v1}, Have a very nice ${v2} !")
#[1] "Hi Tom, Have a very nice day !"

在命名列表中作为参数提供的变量

stringr::str_interp(
  "Hi ${v1}, Have a very nice ${v2} !",
  list("v1" = "Tom", "v2" = "day"))
#[1] "Hi Tom, Have a very nice day !"

向量中定义的变量

values <- c("Tom", "day")
stringr::str_interp(
  "Hi ${v1}, Have a very nice ${v2} !",
  setNames(as.list(values), paste0("v", seq_along(values)))
)
#[1] "Hi Tom, Have a very nice day !"

请注意,value向量只能保存一种类型的数据(列表更灵活),并且数据按照提供的顺序插入。

于 2017-02-28T17:14:46.270 回答