Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use sprintf with a vector rather than a variable number of arguments in R

Tags:

r

printf

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")
like image 588
ichbinallen Avatar asked Aug 31 '18 18:08

ichbinallen


People also ask

What is sprintf () in R?

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.

What is variable argument number?

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.

What does sprintf do?

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.

Where is sprintf defined in C?

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.


1 Answers

We can use do.call

do.call(sprintf, c(fmt = base_string, as.list(v1)))

data

v1 <- c("foo", "bar", "baz")
like image 124
akrun Avatar answered Nov 11 '22 10:11

akrun