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")
sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list. Syntax: sprintf(format, values) Parameter: format: Format of printing the values. values: to be passed into format.
To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.
sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.
The function is declared in C as: int sprintf(char *str, const char *format, [arg1, arg2, ... ]); where, str is a character array on which data is written.
We can use do.call
do.call(sprintf, c(fmt = base_string, as.list(v1)))
v1 <- c("foo", "bar", "baz")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With