Introduction.

Random numbers are required to be generated in epidemiology for a multitude of reasons. Some of the common reasons for generating random numbers are
1. To select a random sample of participants in a study.
2. To assign a random number for anonymising study dataset.
3. To assign a random number for allocation concealment.

Contents.

Though there are multiple ways of generating random numbers, this script is an illustrative example wherein 800 discrete random numbers (integers) will be generated using R. Subsequently, the numbers will be converted into an alpha numeric format.
Alpha numeric format has additional advantage as it can help in distinguishing multiple projects. For example, project 1 and project 2 can have proj1_123 and proj2_123 as random numbers.

Random number generation.

We will generate a dataframe with 800 random numbers within 1 to 9999 without replacement (no duplicates).

set.seed(5197) # for reproducibility
list <- as.data.frame(sample.int( 
  9999,
  800,
  replace = FALSE
))

Renaming the random number column as “list” (Optional)

list <- rename(list,
       "list" = `sample.int(9999, 800, replace = FALSE)`)

Conversion to alpha numeric.

The random numbers belong to integer class. They need to be converted to character class and then made alpha numeric by using stringr package.
In this example, we will be generating alpha numeric random numbers with prefix “CD” and length of 6.
It is a good practice to have same length as it ease out printing of barcodes subsequently, if required.

list$list <- if_else(
  stringr::str_length(list$list)==4,
  stringr::str_c("CD", list$list, sep = ""),
  if_else(
    stringr::str_length(list$list)==3,
    stringr::str_c("CD0", list$list, sep = ""), 
    if_else(
      stringr::str_length(list$list)==2,
      stringr::str_c("CD00", list$list, sep = ""),
      if_else(
        stringr::str_length(list$list)==1,
        stringr::str_c("CD000", list$list, sep = ""),
        NULL
      )
    )
  )
)

Lets see the first 10 random numbers generated and ready for use.

head(list, 10)
##      list
## 1  CD2696
## 2  CD3844
## 3  CD6724
## 4  CD0316
## 5  CD9323
## 6  CD3181
## 7  CD8297
## 8  CD9696
## 9  CD3891
## 10 CD9209