Reputation: 1069
I would like to use the sprintf
function in R with a variable number of arguments. Can I bundle these arguments together in a character vector or list in order to avoid supplying these arguments to sprintf
individually?
An example will clarify:
base_string = "(1) %s, (2) %s, (3) %s"
sprintf(base_string, "foo", "bar", "baz") # this works
sprintf(base_string, c("foo", "bar", "baz")) # this doesn't work
In Python I can accomplish this with
base_string = "(1) %s, (2) %s, (3) %s"
base_string % ("foo", "bar", "baz")
Upvotes: 10
Views: 3020
Reputation: 887078
We can use do.call
do.call(sprintf, c(fmt = base_string, as.list(v1)))
v1 <- c("foo", "bar", "baz")
Upvotes: 16