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.