Movatterモバイル変換


[0]ホーム

URL:


sprintf {base}R Documentation

Use C-style String Formatting Commands

Description

A wrapper for the C functionsprintf, that returns a charactervector containing a formatted combination of text and variable values.

Usage

sprintf(fmt, ...)gettextf(fmt, ..., domain = NULL, trim = TRUE)

Arguments

fmt

a character vector of format strings, each of up to 8192 bytes.

...

values to be passed intofmt. Only logical,integer, real and character vectors are supported, but some coercionwill be done: see the ‘Details’ section. Up to 100.

trim,domain

seegettext.

Details

sprintf is a wrapper for the systemsprintf C-libraryfunction. Attempts are made to check that the mode of the valuespassed match the format supplied, andR's special values (NA,Inf,-Inf andNaN) are handled correctly.

gettextf is a convenience function which provides C-stylestring formatting with possible translation of the format string.

The arguments (includingfmt) are recycled if possible a wholenumber of times to the length of the longest, and then the formattingis done in parallel. Zero-length arguments are allowed and will givea zero-length result. All arguments are evaluated even if unused, andhence some types (e.g.,"symbol" or"language", seetypeof) are not allowed. Arguments unused byfmtresult in a warning. (The format%.0s can be used to“skip” an argument.)

The following is abstracted from:however the actual implementation will follow the C99standard and fine details (especially the behaviour under user error)may depend on the platform. References to numbered arguments come fromPOSIX.

The stringfmt contains normal characters,which are passed through to the output string, and also conversionspecifications which operate on the arguments provided through.... The allowed conversion specifications start with a% and end with one of the letters in the setaAdifeEgGosxX%. These letters denote the following types:

d,i,o,x,X

Integervalue,o being octal,x andX being hexadecimal (using the same case fora-f as the code). Numeric variables with exactly integervalues will be coerced to integer. Formatsd andican also be used for logical variables, which will be converted to0,1 orNA.

f

Double precision value, in “fixedpoint” decimal notation of the form ‘⁠"[-]mmm.ddd"⁠’. The number ofdecimal places ("d") is specified by the precision: the default is 6;a precision of 0 suppresses the decimal point. Non-finite valuesare converted toNA,NaN or (perhaps a sign followedby)Inf.

e,E

Double precision value, in“exponential” decimal notation of theform[-]m.ddde[+-]xx or[-]m.dddE[+-]xx.

g,G

Double precision value, in%e or%E format if the exponent is less than -4 or greater than orequal to the precision, and%f format otherwise.(The precision (default 6) specifies the number ofsignificant digits here, whereas in%f, %e, it isthe number of digits after the decimal point.)

a,A

Double precision value, in binary notationof the form[-]0xh.hhhp[+-]d. This is a binary fractionexpressed in hex multiplied by a (decimal) power of 2. The numberof hex digits after the decimal point is specified by the precision:the default is enough digits to represent exactly the internalbinary representation. Non-finite values are converted toNA,NaN or (perhaps a sign followed by)Inf. Format%a uses lower-case forx,p and the hexvalues: format%A uses upper-case.

This should be supported on all platforms as it is a feature of C99.The format is not uniquely defined: although it would be possibleto make the leadingh always zero or one, this is notalways done. Most systems will suppress trailing zeros, but a fewdo not. On a well-written platform, for normal numbers there willbe a leading one before the decimal point plus (by default) 13hexadecimal digits, hence 53 bits. The treatment of denormalized(aka ‘subnormal’) numbers is very platform-dependent.

s

Character string. CharacterNAs areconverted to"NA".

%

Literal% (none of the extra formattingcharacters given below are permitted in this case).

Conversion byas.character is used for non-characterarguments withs and byas.double fornon-double arguments withf, e, E, g, G. NB: the length isdetermined before conversion, so do not rely on the internalcoercion if this would change the length. The coercion is done onlyonce, so iflength(fmt) > 1 then all elements must expect thesame types of arguments.

In addition, between the initial% and the terminatingconversion character there may be, in any order:

m.n

Two numbers separated by a period, denoting thefield width (m) and the precision (n).

-

Left adjustment of converted argument in its field.

+

Always print number with sign: by default onlynegative numbers are printed with a sign.

a space

Prefix a space if the first character is not a sign.

0

For numbers, pad to the field width with leadingzeros. For characters, this zero-pads on some platforms and isignored on others.

#

specifies “alternate output” for numbers, itsaction depending on the type:Forx orX,0x or0X will be prefixedto a non-zero result. Fore,e,f,gandG, the output will always have a decimal point; forg andG, trailing zeros will not be removed.

Further, immediately after% may come1$ to99$to refer to a numbered argument: this allows arguments to bereferenced out of order and is mainly intended for translators oferror messages. If this is done it is best if all formats arenumbered: if not the unnumbered ones process the arguments in order.See the examples. This notation allows arguments to be used more thanonce, in which case they must be used as the same type (integer,double or character).

A field width or precision (but not both) may be indicated by anasterisk*: in this case an argument specifies the desirednumber. A negative field width is taken as a '-' flag followed by apositive field width. A negative precision is treated as if theprecision were omitted. The argument should be integer, but a doubleargument will be coerced to integer.

There is a limit of 8192 bytes on elements offmt, and onstrings included from a single%letter conversionspecification.

Field widths and precisions of%s conversions are interpretedas bytes, not characters, as described in the C standard.

The C doubles used forR numerical vectors have signed zeros, whichsprintf may output as-0,-0.000 ....

Value

A character vector of length that of the longest input. If anyelement offmt or any character argument is declared as UTF-8,the element of the result will be in UTF-8 and have the encodingdeclared as UTF-8. Otherwise it will be in the current locale'sencoding.

Warning

The format string is passed down the OS'ssprintf function, andincorrect formats can cause the latter to crash theR process .Rdoes perform sanity checks on the format, but not all possible usererrors on all platforms have been tested, and some might be terminal.

The behaviour on inputs not documented here is ‘undefined’,which means it is allowed to differ by platform.

Author(s)

Original code by Jonathan Rougier.

References

The C Standards, especially ISO/IEC 9899:1999 for ‘C99’. Linkscan be found athttps://developer.r-project.org/Portability.html.

https://pubs.opengroup.org/onlinepubs/9699919799/functions/snprintf.htmlfor POSIX extensions such as numbered arguments.

man sprintf on a Unix-alike system.

See Also

formatC for a way of formatting vectors of numbers in asimilar fashion.

paste for another way of creating a vector combiningtext and values.

gettext for the mechanisms for the automated translationof 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)      # OKtry(sprintf("%s is %i feet tall\n", "Sven", 7.1)) # not OK    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 justifiedsprintf("%e", pi)sprintf("%E", pi)sprintf("%g", pi)sprintf("%g",   1e6 * pi) # -> exponentialsprintf("%.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 %Xxx <- 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:18sprintf(paste0("e with %2d digits = %.", n, "g"), n, exp(1))## Platform-dependent bad example: may pad with spaces or zeroessprintf("%09s", month.name)## Using arguments out of ordersprintf("second %2$1.0f, first %1$5.2f, third %3$1.0f", pi, 2, 3)## Using asterisk for width or precisionsprintf("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 argumentssprintf("%s %d", "test", 1:3)## binary output showing rounding/representation errorsx <- seq(0, 1.0, 0.1); y <- c(0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1)cbind(x, sprintf("%a", x), sprintf("%a", y))

[Packagebase version 4.6.0Index]

[8]ページ先頭

©2009-2025 Movatter.jp