Skip to content

Create numbered names that will be alphanumerically sorted as expected (in R)

August 13, 2012

Sorting numbered names sucks in R:

> sort(paste('name', 1:15, sep = ''))
 [1] "name1"  "name10" "name11" "name12" "name13" "name14"
 [7] "name15" "name2"  "name3"  "name4"  "name5"  "name6" 
[13] "name7"  "name8"  "name9" 
> 

That’s not right at all!

This function makes things better:

#' @param n Number of names.
#' @param prefix Character prefix to go in front of the numbers.
#' @return A character vector of numbered names.
numnames <- function(n, prefix = "name"){
	n <- as.integer(n)
	if(n < 1) stop("number of names must be one or more")
	zeropad.code <- paste("%0", nchar(n), ".0f", sep = "")
	numpart <- sprintf(zeropad.code, 1:n)
	paste(prefix, numpart, sep = "")
}

For example:

> sort(numnames(15))
 [1] "name01" "name02" "name03" "name04" "name05" "name06"
 [7] "name07" "name08" "name09" "name10" "name11" "name12"
[13] "name13" "name14" "name15"
> 
About these ads
2 Comments leave one →
  1. September 30, 2012 1:31 pm

    :)

  2. October 1, 2012 6:14 pm

    sprintf(‘name_%02d’, 1:15)

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

Follow

Get every new post delivered to your Inbox.

Join 76 other followers

%d bloggers like this: