The R Project SVN R

Rev

Rev 61433 | Rev 65147 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/base/man/sprintf.Rd
2
% Part of the R package, http://www.R-project.org
59168 ripley 3
% Copyright 1995-2012 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
19133 maechler 6
\name{sprintf}
56186 murdoch 7
\alias{sprintf}
33351 hornik 8
\alias{gettextf}
19133 maechler 9
\title{Use C-style String Formatting Commands}
10
\description{
33351 hornik 11
  A wrapper for the C function \code{sprintf}, that returns a character
34218 ripley 12
  vector containing a formatted combination of text and variable values.
19133 maechler 13
}
14
\usage{
15
sprintf(fmt, \dots)
33351 hornik 16
gettextf(fmt, \dots, domain = NULL)
19133 maechler 17
}
18
\arguments{
44712 ripley 19
  \item{fmt}{a character vector of format strings, each of up to 8192 bytes.}
32799 ripley 20
  \item{\dots}{values to be passed into \code{fmt}.  Only logical,
33548 ripley 21
    integer, real and character vectors are supported, but some coercion
44184 ripley 22
    will be done: see the \sQuote{Details} section.}
33351 hornik 23
  \item{domain}{see \code{\link{gettext}}.}
19133 maechler 24
}
25
\details{
33351 hornik 26
  \code{sprintf} is a wrapper for the system \code{sprintf} C-library
27
  function.  Attempts are made to check that the mode of the values
28
  passed match the format supplied, and \R's special values (\code{NA},
29
  \code{Inf}, \code{-Inf} and \code{NaN}) are handled correctly.
33194 ripley 30
 
33351 hornik 31
  \code{gettextf} is a convenience function which provides C-style
33548 ripley 32
  string formatting with possible translation of the format string.
33351 hornik 33
 
33203 ripley 34
  The arguments (including \code{fmt}) are recycled if possible a whole
35
  number of times to the length of the longest, and then the formatting
57520 ripley 36
  is done in parallel.  Zero-length arguments are allowed and will give
37
  a zero-length result.  All arguments are evaluated even if unused, and
38
  hence some types (e.g., \code{"symbol"} or \code{"language"}, see
39
  \code{\link{typeof}}) are not allowed.
48295 maechler 40
 
59168 ripley 41
  The following is abstracted from Kernighan and Ritchie (see
42
  References): however the actual implementation will follow the C99
43
  standard and fine details (especially the behaviour under user error)
44
  may depend on the platform.
45
 
46
  The string \code{fmt} contains normal characters,
44700 ripley 47
  which are passed through to the output string, and also conversion
48
  specifications which operate on the arguments provided through
49
  \code{\dots}.  The allowed conversion specifications start with a
50
  \code{\%} and end with one of the letters in the set
49773 ripley 51
  \code{aAdifeEgGosxX\%}.  These letters denote the following types:
19133 maechler 52
 
53
  \describe{
62069 hornik 54
    \item{\code{d}, \code{i}, \code{o}, \code{x}, \code{X}}{Integer
55
      value, \code{o} being octal, 
49773 ripley 56
      \code{x} and \code{X} being hexadecimal (using the same case for
57
      \code{a-f} as the code).  Numeric variables with exactly integer
55555 ripley 58
      values will be coerced to integer.  Formats \code{d} and \code{i}
49773 ripley 59
      can also be used for logical variables, which will be converted to
60
      \code{0}, \code{1} or \code{NA}.
33548 ripley 61
    }
48376 maechler 62
    \item{\code{f}}{Double precision value, in \dQuote{\bold{f}ixed
49972 ripley 63
        point} decimal notation of the form "[-]mmm.ddd".  The number of
48426 maechler 64
      decimal places ("d") is specified by the precision: the default is 6;
65
      a precision of 0 suppresses the decimal point.  Non-finite values
48376 maechler 66
      are converted to \code{NA}, \code{NaN} or (perhaps a sign followed
67
      by) \code{Inf}.
33117 ripley 68
    }
62069 hornik 69
    \item{\code{e}, \code{E}}{Double precision value, in
48376 maechler 70
      \dQuote{\bold{e}xponential} decimal notation of the
33117 ripley 71
      form \code{[-]m.ddde[+-]xx} or \code{[-]m.dddE[+-]xx}.
72
    }
62069 hornik 73
    \item{\code{g}, \code{G}}{Double precision value, in \code{\%e} or
19133 maechler 74
      \code{\%E} format if the exponent is less than -4 or greater than or
33117 ripley 75
      equal to the precision, and \code{\%f} format otherwise.
48426 maechler 76
      (The precision (default 6) specifies the number of
77
      \emph{significant} digits here, whereas in \code{\%f, \%e}, it is
78
      the number of digits after the decimal point.)
33117 ripley 79
    }
62069 hornik 80
    \item{\code{a}, \code{A}}{Double precision value, in binary notation
81
      of the form \code{[-]0xh.hhhp[+-]d}.  This is a binary fraction
46517 ripley 82
      expressed in hex multiplied by a (decimal) power of 2.  The number
83
      of hex digits after the decimal point is specified by the precision:
84
      the default is enough digits to represent exactly the internal
85
      binary representation.  Non-finite values are converted to \code{NA},
46521 ripley 86
      \code{NaN} or (perhaps a sign followed by) \code{Inf}.  Format
87
      \code{\%a} uses lower-case for \code{x}, \code{p} and the hex
88
      values: format \code{\%A} uses upper-case.
48295 maechler 89
 
54462 ripley 90
      This should be supported on all platforms as it is a feature of C99.
46521 ripley 91
      The format is not uniquely defined: although it would be possible
92
      to make the leading \code{h} always zero or one, this is not
46525 ripley 93
      always done.  Most systems will suppress trailing zeros, but a few
48376 maechler 94
      do not.  On a well-written platform, for normal numbers there will
46525 ripley 95
      be a leading one before the decimal point plus (by default) 13
54673 ripley 96
      hexadecimal digits, hence 53 bits.  The treatment of denormalized
97
      (aka \sQuote{subnormal}) numbers is very platform-dependent.
46517 ripley 98
    }
48376 maechler 99
    \item{\code{s}}{Character string.  Character \code{NA}s are
44700 ripley 100
      converted to \code{"NA"}.
101
    }
102
    \item{\code{\%}}{Literal \code{\%} (none of the extra formatting
103
      characters given below are permitted in this case).
104
    }
19133 maechler 105
  }
44700 ripley 106
  Conversion by \code{\link{as.character}} is used for non-character
107
  arguments with \code{s} and by \code{\link{as.double}} for
108
  non-double arguments with \code{f, e, E, g, G}.  NB: the length is
109
  determined before conversion, so do not rely on the internal
44711 ripley 110
  coercion if this would change the length.  The coercion is done only
111
  once, so if \code{length(fmt) > 1} then all elements must expect the
48295 maechler 112
  same types of arguments.
113
 
19133 maechler 114
  In addition, between the initial \code{\%} and the terminating
115
  conversion character there may be, in any order:
116
 
117
  \describe{
118
    \item{\code{m.n}}{Two numbers separated by a period, denoting the
44700 ripley 119
      field width (\code{m}) and the precision (\code{n}).}
120
    \item{\code{-}}{Left adjustment of converted argument in its field.}
121
    \item{\code{+}}{Always print number with sign: by default only
122
      negative numbers are printed with a sign.}
123
    \item{a space}{Prefix a space if the first character is not a sign.}
124
    \item{\code{0}}{For numbers, pad to the field width with leading zeros.}
48295 maechler 125
    \item{\code{#}}{specifies \dQuote{alternate output} for numbers, its
126
      action depending on the type:
127
      For \code{x} or \code{X}, \code{0x} or \code{0X} will be prefixed
128
      to a non-zero result.  For \code{e}, \code{e}, \code{f}, \code{g}
129
      and \code{G}, the output will always have a decimal point; for
130
      \code{g} and \code{G}, trailing zeros will not be removed.
131
    }
19133 maechler 132
  }
38402 ripley 133
  Further, immediately after \code{\%} may come \code{1$} to \code{99$}
44700 ripley 134
  to refer to numbered argument: this allows arguments to be
38402 ripley 135
  referenced out of order and is mainly intended for translators of
136
  error messages.  If this is done it is best if all formats are
137
  numbered: if not the unnumbered ones process the arguments in order.
44700 ripley 138
  See the examples.  This notation allows arguments to be used more than
139
  once, in which case they must be used as the same type (integer,
140
  double or character).
32799 ripley 141
 
38402 ripley 142
  A field width or precision (but not both) may be indicated by an
44700 ripley 143
  asterisk \code{*}: in this case an argument specifies the desired
144
  number.  A negative field width is taken as a '-' flag followed by a
145
  positive field width.  A negative precision is treated as if the
44711 ripley 146
  precision were omitted.  The argument should be integer, but a double
147
  argument will be coerced to integer.
44700 ripley 148
 
48468 maechler 149
  There is a limit of 8192 bytes on elements of \code{fmt}, and on
48399 maechler 150
  strings included from a single \code{\%}\emph{letter} conversion
151
  specification.
45847 ripley 152
 
153
  Field widths and precisions of \code{\%s} conversions are interpreted
154
  as bytes, not characters, as described in the C standard.
19133 maechler 155
}
49649 ripley 156
%% (for #) This is from Kernighan & Ritchie, p. 243:
157
%% For \code{o}, the first digit will be zero.
19133 maechler 158
 
49649 ripley 159
 
19717 ripley 160
\value{
45847 ripley 161
  A character vector of length that of the longest input.  If any
162
  element of \code{fmt} or any character argument is declared as UTF-8,
163
  the element of the result will be in UTF-8 and have the encoding
164
  declared as UTF-8.  Otherwise it will be in the current locale's
165
  encoding.
19717 ripley 166
}
19133 maechler 167
 
46935 ripley 168
\section{Warning}{
169
  The format string is passed down the OS's \code{sprintf} function, and
170
  incorrect formats can cause the latter to crash the \R process .  \R
48468 maechler 171
  does perform sanity checks on the format, and since \R 2.10.0, we have
172
  not seen crashes anymore.  But not all possible user errors on all
173
  platforms have been tested, and some might be terminal.
61433 ripley 174
 
59168 ripley 175
  The behaviour on inputs not documented here is \sQuote{undefined},
176
  which means it is allowed to differ by platform.
46935 ripley 177
}
178
 
19133 maechler 179
\references{
180
  Kernighan, B. W. and Ritchie, D. M. (1988)
181
  \emph{The C Programming Language.} Second edition, Prentice Hall.
59168 ripley 182
  Describes the format options in table B-1 in the Appendix.
183
 
184
  The C Standards, especially ISO/IEC 9899:1999 for \sQuote{C99}.  Links
185
  can be found at \url{http://developer.r-project.org/Portability.html}.
186
 
187
  \command{man sprintf} on a Unix-alike system.
19133 maechler 188
}
189
 
19717 ripley 190
\author{
46935 ripley 191
  Original code by Jonathan Rougier.
19717 ripley 192
}
19133 maechler 193
 
19692 maechler 194
\seealso{
33351 hornik 195
  \code{\link{formatC}} for a way of formatting vectors of numbers in a
196
  similar fashion.
19692 maechler 197
 
33351 hornik 198
  \code{\link{paste}} for another way of creating a vector combining
199
  text and values.
200
 
201
  \code{\link{gettext}} for the mechanisms for the automated translation
202
  of text.
19133 maechler 203
}
204
 
50414 ripley 205
% Escape all the '%' here !
19133 maechler 206
\examples{
207
## be careful with the format: most things in R are floats
33174 ripley 208
## only integer-valued reals get coerced to integer.
19133 maechler 209
 
33194 ripley 210
sprintf("\%s is \%f feet tall\n", "Sven", 7.1)      # OK
33174 ripley 211
try(sprintf("\%s is \%i feet tall\n", "Sven", 7.1)) # not OK
48376 maechler 212
    sprintf("\%s is \%i feet tall\n", "Sven", 7  )  # OK
19133 maechler 213
 
214
## use a literal \% :
215
 
216
sprintf("\%.0f\%\% said yes (out of a sample of size \%.0f)", 66.666, 3)
217
 
218
## various formats of pi :
219
 
220
sprintf("\%f", pi)
221
sprintf("\%.3f", pi)
222
sprintf("\%1.0f", pi)
223
sprintf("\%5.1f", pi)
224
sprintf("\%05.1f", pi)
225
sprintf("\%+f", pi)
226
sprintf("\% f", pi)
33194 ripley 227
sprintf("\%-10f", pi) # left justified
19133 maechler 228
sprintf("\%e", pi)
229
sprintf("\%E", pi)
230
sprintf("\%g", pi)
231
sprintf("\%g",   1e6 * pi) # -> exponential
232
sprintf("\%.9g", 1e6 * pi) # -> "fixed"
233
sprintf("\%G", 1e-6 * pi)
234
 
235
## no truncation:
61150 ripley 236
sprintf("\%1.f", 101)
19133 maechler 237
 
33218 ripley 238
## re-use one argument three times, show difference between \%x and \%X
239
xx <- sprintf("\%1$d \%1$x \%1$X", 0:15)
61150 ripley 240
xx <- matrix(xx, dimnames = list(rep("", 16), "\%d\%x\%X"))
241
noquote(format(xx, justify = "right"))
33203 ripley 242
 
19133 maechler 243
## More sophisticated:
244
 
33194 ripley 245
sprintf("min 10-char string '\%10s'",
246
        c("a", "ABC", "and an even longer one"))
19133 maechler 247
 
33194 ripley 248
n <- 1:18
61156 ripley 249
sprintf(paste0("e with \%2d digits = \%.", n, "g"), n, exp(1))
33117 ripley 250
 
33174 ripley 251
## Using arguments out of order
33117 ripley 252
sprintf("second \%2$1.0f, first \%1$5.2f, third \%3$1.0f", pi, 2, 3)
33194 ripley 253
 
35625 urbaneks 254
## Using asterisk for width or precision
255
sprintf("precision \%.*f, width '\%*.3f'", 3, pi, 8, pi)
256
 
37193 ripley 257
## Asterisk and argument re-use, 'e' example reiterated:
35625 urbaneks 258
sprintf("e with \%1$2d digits = \%2$.*1$g", n, exp(1))
259
 
48295 maechler 260
## re-cycle arguments
33194 ripley 261
sprintf("\%s \%d", "test", 1:3)
46517 ripley 262
 
263
## binary output showing rounding/representation errors
264
x <- seq(0, 1.0, 0.1); y <- c(0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1)
265
cbind(x, sprintf("\%a", x), sprintf("\%a", y))
19133 maechler 266
}
267
\keyword{print}
268
\keyword{character}