[R] sprintf

Marc Schwartz (via MN) mschwartz at mn.rr.com
Fri Feb 17 21:27:41 CET 2006


On Fri, 2006-02-17 at 12:01 -0800, J.M. Breiwick wrote:
> Hi,
> 
> I want to use sprintf with vectors whose lengths vary.
> As an example: x = c(2,4,6,10)
> sprintf("%i%5f%5f%5f",x[1],x[2],x[3],x[4]) works. But if I have to compute 
> the length of x within a function then I cannot list all for format codes 
> and sprintf apparently will not accept just "x" - it wants one value for 
> each format code as in the above example. Does anyone know a way to handle 
> this? And is there a way to repeat the format code like in Fortran (e.g. 
> 5F4.1)? Thanks.
> 
> Jeff B.

Is the format of the vector 'x' predictable?  In other words, will the
first element always be printed as an integer with the rest (of unknown
length) printed as floats?

Keep in mind that sprintf() is vectorized.

So:

x <- c(2, 4, 6, 10)

> c(sprintf("%i", x[1]), sprintf("%5f", x[-1]))
[1] "2"         "4.000000"  "6.000000"  "10.000000"


> x <- seq(2, 20, 2)
> x
 [1]  2  4  6  8 10 12 14 16 18 20

# Same code here
> c(sprintf("%i", x[1]), sprintf("%5f", x[-1]))
 [1] "2"         "4.000000"  "6.000000"  "8.000000"  "10.000000"
 [6] "12.000000" "14.000000" "16.000000" "18.000000" "20.000000"


Does that get what you want?

BTW, please do not create a new post by responding to a different
thread. It plays havoc with the list archive making it difficult to
search for your post and any replies.

HTH,

Marc Schwartz




More information about the R-help mailing list