Re: [R] sprintf

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Sat 18 Feb 2006 - 07:27:41 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Feb 18 07:32:02 2006

This archive was generated by hypermail 2.1.8 : Mon 20 Feb 2006 - 14:08:40 EST