有没有可以替代 paste 的功能?我想知道R中是否存在这样的东西:
> buildString ( "Hi {1}, Have a very nice {2} ! " , c("Tom", "day") )
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!"
该sprintf
功能是其他人提到的一种方法,这是使用该gsubfn
包的另一种方法:
> library(gsubfn)
> who <- "Tom"
> time <- "day"
> fn$paste("Hi $who, have a nice $time")
[1] "Hi Tom, have a nice day"
我认为您正在寻找 sprintf。
具体来说:
sprintf("Hi %s, Have a very nice %s!","Tom","day")
该whisker
软件包在这方面做得很好,值得更广泛的赞赏:
require(whisker)
whisker.render ( "Hi {{name}}, Have a very nice {{noun}} ! " , list(name="Tom", noun="day") )
在 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
向量只能保存一种类型的数据(列表更灵活),并且数据按照提供的顺序插入。