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

One thought on “Generating unique random IDs

  1. { Nice job, really good post mate | I will definitely recommend this to my friends | keep it up! Thanks | This is really amazing post, i think i will come back often for read some news| The post is really great, i have learned lot from this post, thank’s| thank you very much for sharing | Everything is interesting | thanks good for topic | I will definitely recommend this to my friends| This was an interesting post | quite intriguing post | Thank a lot good post!}

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