Skip to content

Converting a numeric vector to a character vector (such that all elements have the same number of characters)

August 13, 2012

In R, its often useful to convert a numeric vector to character (e.g. plot legends). When doing this its nice when the number of characters used for each number is the same, because things look nicer that way — they line up better. It also helps to have the decimal in the same place for all the numbers. The way to do it is sprintf.

But I hate sprintf. Probably because I’m an R brat (i.e. someone who grew up more with R than with C, and so doesn’t know about all kinds of computer science things that are useful for good scientific programming). Still, I hate dealing with sprintf, which is what you need to solve the problem in the post title. Here’s a function that’s more intuitive to me:

round.char <- function(x, digits = 0){
	if(digits < 0) digits <- 0
	rd <- round(digits)
	nc <- max(nchar(trunc(x))) + rd + 1
	fmt <- paste('%0', nc, '.', rd, 'f', sep = '')
	sprintf(fmt, x)
}

This function uses sprintf, but I’ve wrapped it in more intuitive syntactic sugar so I never have to think about sprintf again when doing this task.

Here’s an example,

> set.seed(1)
> x <- c(rnorm(2), rnorm(2, sd = 1000))
> round.char(x, 2)
[1] "-000.63" "0000.18" "-835.63" "1595.28"
> nchar(round.char(x, 2))
[1] 7 7 7 7
> 

As always…I’d love to hear of better ways to do this.

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: