Generating unique random IDs

[This article was first published on Matt's Stats n stuff » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)
  }

To leave a comment for the author, please follow the link and comment on their blog: Matt's Stats n stuff » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)