Is there a function that can be an alternative to paste ? I would like to know if something like this exists in R:
> buildString ( \"Hi {1}, Have a very nice
With version 1.1.0 (CRAN release on 2016-08-19), the stringr package has gained a string interpolation function str_interp().
With str_interp() the following use cases are possible:
Variables defined in the environment
v1 <- "Tom"
v2 <- "day"
stringr::str_interp("Hi ${v1}, Have a very nice ${v2} !")
#[1] "Hi Tom, Have a very nice day !"
Variables provided in a named list as parameter
stringr::str_interp(
"Hi ${v1}, Have a very nice ${v2} !",
list("v1" = "Tom", "v2" = "day"))
#[1] "Hi Tom, Have a very nice day !"
Variables defined in a vector
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 !"
Note that the value vector can only hold data of one type (a list is more flexible) and the data are inserted in the order they are provided.
frankc and DWin are right to point you to sprintf().
If for some reason your replacement parts really will be in the form of a vector (i.e. c("Tom", "day")), you can use do.call() to pass them in to 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!"
The sprintf function is one approach as others have mentioned, here is another approach using the gsubfn package:
> library(gsubfn)
> who <- "Tom"
> time <- "day"
> fn$paste("Hi $who, have a nice $time")
[1] "Hi Tom, have a nice day"
I think you are looking for sprintf.
Specifically:
sprintf("Hi %s, Have a very nice %s!","Tom","day")
The whisker package does this very well, and deserves wider appreciation:
require(whisker)
whisker.render ( "Hi {{name}}, Have a very nice {{noun}} ! " , list(name="Tom", noun="day") )