[R] Formatting numbers for printing

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jun 8 23:54:07 CEST 2006


On 6/8/2006 5:42 PM, Dennis Fisher wrote:
> Colleagues
> 
> I have numbers like "12012" that I will be printing in a graphic.  I  
> would like to format them as follows: 012-012, i.e., the first two  
> digits padded to the left by a zero, followed by a dash, followed by  
> the final three digits, also padded to the left by zeros.
> 
> I can do this with brute force:
> 
> FirstPart			<- sprintf("%03d", floor(Number / 1000))
> SecondPart		<- sprintf("%03d", WhichID %% 1000)
> Combined		<- paste(FirstPart, "-", SecondPart, sep="")
> 
> But, I suspect that there is some more clever means to accomplish  
> this using formatC or sprintf.  Unfortunately, the help pages don't  
> provide sufficient insight.  I would appreciate any tricks to  
> accomplish this.
> 

I think you need to do the separation into two parts as you did (or 
using %/%), but it can all be one sprintf:

sprintf("%03d-%03d", Number %/% 1000, Number %% 1000)

Duncan Murdoch



More information about the R-help mailing list