Generating unique random IDs

Recently I was asked to help create random IDs for someone. At first I thought, ‘Ah yup, 1:x (1,2,3, …,x), job done’. Then I thought that there had to be a R function/package to create better looking IDs, to which I didn’t find one, if there is, please let me know.

In the mean time I wrote this, which puts a random letter at the start, followed by random (shuffled) numbers. Using ‘sprintf’ allows the keeping in of leading 0′s, this way all your ID’s are the same character width, multiplying by 100 is purely to avoid having small (<3) ID’s created, this can be changed to 1, if you choose. Not 100% on the reason for leading with a letter, but it seems common in ID’s, perhaps to avoid something like ‘id_col/3′ actually running ┬áif you used only numbers…

idmaker <- function(x)
  {
    max.val = x*100
    count <- nchar(as.character(max.val))                       # find out how many 'numbers' each ID will have after the letter
    size <- paste("%0",count,"d",sep="")                        # set the variable to be fed into 'sprintf' to ensure we have leading 0's
    lets <- toupper(sample(letters,x, replace=T))               # randomising the letters 
    nums <- sprintf(size,sample(1:max.val)[1:x])                # randominsing the numbers, and ensuing they all have the same number of characters
    ids <- paste(lets,nums,sep="")                              # joining them together
  return(ids)
  }

Created by Pretty R at inside-R.org

About these ads

2 thoughts on “Generating unique random IDs

    • Thanks Dan. This uses ‘sample’ in the 5th line when it draws the numbers, the default setting for this is that it will not sample with replacement. Therefore each number drawn from the list (which is then appended to the leading letter) is unique.

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