粘贴的替代功能

时间:2012-04-26 20:40:05

标签: string r function

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

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

5 个答案:

答案 0 :(得分:25)

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

答案 1 :(得分:21)

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

> library(gsubfn)
> who <- "Tom"
> time <- "day"
> fn$paste("Hi $who, have a nice $time")
[1] "Hi Tom, have a nice day"

答案 2 :(得分:18)

我认为你正在寻找sprintf。

具体做法是:

sprintf("Hi %s, Have a very nice %s!","Tom","day")

答案 3 :(得分:17)

whisker套餐做得非常好,值得更广泛的赞赏:

require(whisker)
whisker.render ( "Hi {{name}}, Have a very nice {{noun}} ! " , list(name="Tom", noun="day") )

答案 4 :(得分:2)

对于版本1.1.0(2016-08-19的CRAN版本),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向量只能保存一种类型的数据(列表更灵活),数据按照提供的顺序插入。