Contents

R: Generate Random Strings with Uppercase Letters and Digits

You can generate random strings with combinations of uppercase letters and digits in R by using various functions such as sample() and stri_rand_strings() functions.

The following example explains how to generate random strings with uppercase letters and digits.

Using sample() function

You can use sample() function in R to generate random strings with upper case letters and digits of specified length.

For example, if you want to create random strings of length 8 with upper case letters and digits.

# create upper case string and Digits
all_chars <- c(LETTERS, 0:9)
str_len <- 8

# generate random strings with upper case letters and digits
rand_string <- paste(sample(all_chars, str_len, replace = TRUE), collapse = "")

rand_string

# output
[1] "W1H23UKP"

In the above example, the all_chars variable contains all uppercase letters and digits, and then we use this variable to generate random strings of length 10.

You can see that the random strings of length 10 with uppercase letters and digits have been created using the sample() function in R.

Using stri_rand_strings() function

In addition to sample(), you can use stri_rand_strings() function to generate random strings with uppercase letters and digits of specified length.

For example, if you want to create random strings of length 12 with upper case letters and digits.

# import packages
# install.packages("stringi")
library(stringi)

# generate random strings with upper case letters and digits
str_len = 12
rand_string = stri_rand_strings(1, str_len, pattern = "[A-Z0-9]")

rand_string

# output
[1] "IN3CFSE158PJ"

You can see that the random strings of length 12 with uppercase letters and digits have been created using the stri_rand_strings() function from the stringi R package.

The stri_rand_strings() function could be faster if you want to generate random strings of larger lengths.