Search notes:

R function: sprintf

sprintf is a wrapper around the C function printf.

Basic usage

sprintf("%.3f" , pi);
# "3.142"

sprintf("%5.2f", pi);
# " 3.14"

sprintf("%+f"  , pi); # with sign
# "+3.141593"

sprintf("%-10f", pi); # left adjustment
# "3.141593  "
Github repository about-r, path: /functions/sprintf/basic.R

Omitting quotes

The output of sprintf embeds strings in quotes. These can be omitted by feeding the output of sprintf to cat(…):
vec <- c('foo', 'bar', 'baz');

sprintf('%s', vec);
#
#  [1] "foo" "bar" "baz"

cat(sprintf('%s', vec));
#
#  foo bar baz
Github repository about-r, path: /functions/sprintf/omit-quotes.R

Using the recycling rule

The recycling rule can be applied in sprintf:
cat(
   sprintf('%s - %d', c('foo','bar', 'baz'), 3:8),
   sep ="\n"
)
#
# foo - 3
# bar - 4
# baz - 5
# foo - 6
# bar - 7
# baz - 8
Github repository about-r, path: /functions/sprintf/recycling-rule.R

See also

String related R functions, printing characters
cat(…), message(…), print(…)
Index to (some) R functions
printf in different languages

Index