| sprintf {base} | R Documentation |
Use C-style String Formatting Commands
Description
A wrapper for the C function sprintf, that returns a character
vector containing a formatted combination of text and variable values.
Usage
sprintf(fmt, ...)
gettextf(fmt, ..., domain = NULL)
Arguments
fmt |
a format string. |
... |
values to be passed into |
domain |
see |
Details
sprintf is a wrapper for the system sprintf C-library
function. Attempts are made to check that the mode of the values
passed match the format supplied, and R's special values (NA,
Inf, -Inf and NaN) are handled correctly.
gettextf is a convenience function which provides C-style
string formatting with possible translation of the format string.
The arguments (including fmt) are recycled if possible a whole
number of times to the length of the longest, and then the formatting
is done in parallel.
The following is abstracted from Kernighan and Ritchie
(see References). The string fmt contains normal characters,
which are passed through to the output string, and also special
characters that operate on the arguments provided through
.... Special characters start with a % and end with
one of the letters in the set difeEgGsxX%. These letters
denote the following types:
d, i, x, XInteger value,
xandXbeing hexadecimal (using the same case fora-fas the code). Numeric variables with exactly integer values will be coerced to integer.fDouble precision value, in decimal notation of the form "[-]mmm.ddd". The number of decimal places is specified by the precision: the default is 6; a precision of 0 suppresses the decimal point.
e, EDouble precision value, in decimal notation of the form
[-]m.ddde[+-]xxor[-]m.dddE[+-]xx.g, GDouble precision value, in
%eor%Eformat if the exponent is less than -4 or greater than or equal to the precision, and%fformat otherwise.sCharacter string.
%Literal
%(none of the formatting characters given below are permitted in this case).
as.character is used for non-character arguments with
s and as.double for non-double arguments with
f, e, E, g, G. NB: the length is determined before conversion,
so do not rely on the internal coercion if this would change the
length.
In addition, between the initial % and the terminating
conversion character there may be, in any order:
m.nTwo numbers separated by a period, denoting the field width (
m) and the precision (n)-Left adjustment of converted argument in its field
+Always print number with sign
- a space
Prefix a space if the first number is not a sign
0For numbers, pad to the field width with leading zeros
Further, immediately after % may come 1$ to 99$
to refer to the numbered argument: this allows arguments to be
referenced out of order and is mainly intended for translators of
error messages. If this is done it is best if all formats are
numbered: if not the unnumbered ones process the arguments in order.
See the examples.
A field width or precision (but not both) may be indicated by an
asterisk *. In this case an argument specifies the desired
number. A negative field width is taken as a '-' flag followed by a
positive field width. A negative precision is taken as if the
precision were omitted. The *1$ to *99$ notation for
arguments referenced out of order is also supported.
The result has a length limit, probably 8192 bytes, and attempts to exceed this may result in an error, or truncation with a warning.
Value
A character vector of length that of the longest input.
Character NAs are converted to "NA".
Author(s)
Original code by Jonathan Rougier, J.C.Rougier@durham.ac.uk.
References
Kernighan, B. W. and Ritchie, D. M. (1988) The C Programming Language. Second edition, Prentice Hall. describes the format options in table B-1 in the Appendix.
See Also
formatC for a way of formatting vectors of numbers in a
similar fashion.
paste for another way of creating a vector combining
text and values.
gettext for the mechanisms for the automated translation
of text.
Examples
## be careful with the format: most things in R are floats
## only integer-valued reals get coerced to integer.
sprintf("%s is %f feet tall\n", "Sven", 7.1) # OK
try(sprintf("%s is %i feet tall\n", "Sven", 7.1)) # not OK
try(sprintf("%s is %i feet tall\n", "Sven", 7)) # OK
## use a literal % :
sprintf("%.0f%% said yes (out of a sample of size %.0f)", 66.666, 3)
## various formats of pi :
sprintf("%f", pi)
sprintf("%.3f", pi)
sprintf("%1.0f", pi)
sprintf("%5.1f", pi)
sprintf("%05.1f", pi)
sprintf("%+f", pi)
sprintf("% f", pi)
sprintf("%-10f", pi) # left justified
sprintf("%e", pi)
sprintf("%E", pi)
sprintf("%g", pi)
sprintf("%g", 1e6 * pi) # -> exponential
sprintf("%.9g", 1e6 * pi) # -> "fixed"
sprintf("%G", 1e-6 * pi)
## no truncation:
sprintf("%1.f",101)
## re-use one argument three times, show difference between %x and %X
xx <- sprintf("%1$d %1$x %1$X", 0:15)
xx <- matrix(xx, dimnames=list(rep("", 16), "%d%x%X"))
noquote(format(xx, justify="right"))
## More sophisticated:
sprintf("min 10-char string '%10s'",
c("a", "ABC", "and an even longer one"))
n <- 1:18
sprintf(paste("e with %2d digits = %.",n,"g",sep=""), n, exp(1))
## Using arguments out of order
sprintf("second %2$1.0f, first %1$5.2f, third %3$1.0f", pi, 2, 3)
## Using asterisk for width or precision
sprintf("precision %.*f, width '%*.3f'", 3, pi, 8, pi)
## Asterisk and argument re-use, 'e' example reiterated:
sprintf("e with %1$2d digits = %2$.*1$g", n, exp(1))
## re-cycle arguments
sprintf("%s %d", "test", 1:3)