MadSeb
MadSeb

Reputation: 8234

Alternative function to paste

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 {2} ! " , c("Tom", "day") )

Upvotes: 19

Views: 6108

Answers (5)

Uwe
Uwe

Reputation: 42544

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.

Upvotes: 2

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

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

Upvotes: 27

frankc
frankc

Reputation: 11473

I think you are looking for sprintf.

Specifically:

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

Upvotes: 20

jverzani
jverzani

Reputation: 5700

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

Upvotes: 17

Greg Snow
Greg Snow

Reputation: 49640

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"

Upvotes: 21

Related Questions