Command in R: An example of generating a random string using the “stringi” package

RAnalytics
スポンサーリンク

Sometimes it is necessary to generate random strings. In such cases, the “stri_rand_strings” command from the “stringi” package. Here is an example of creating a dataset for reference.

Checked with R version 4.1.2.

スポンサーリンク

Example

See the command and package help for details.

#Install the tidyverse package if it is not already present
if(!require("tidyverse", quietly = TRUE)){
  install.packages("tidyverse");require("tidyverse")
}

#Install the tidyverse package if it is not already present
if(!require("stringi", quietly = TRUE)){
  install.packages("stringi");require("stringi")
}

#String a specified length from a specified pattern: stri_rand_strings command
#Specifies the number of generated strings: n option
#Specify the length of the string: length option
#Specify a pattern: pattern option
stri_rand_strings(n = 3, length = 4, pattern = "[a-zあ-んア-ンA-Z0-9]")
[1] "るばGガ" "iニョあ" "tVヲっ"

###Creating Data#####
n <- 300

#Exsample 1
#Using tidyr,stringi package and replace command
TestData1 <- tibble(Time = paste0("Time", formatC(1:n, width = 2, flag = "0")),
                    Word = paste0("Word", formatC(1:n, width = 2, flag = "0")),
                    Strings = NA) %>%
  group_by(Time) %>%
  mutate_at(vars(-group_cols()),
            ~replace(., is.na(.),
                     stri_rand_strings(n = 1, length = 4,
                                       pattern = "[a-zあ-んア-ンA-Z0-9]"))) %>%
  spread(key = Word, Strings)

#Exsample 2
#Using stringi package
TestData2 <- data.frame(paste0("Group", formatC(1:n, width = 2, flag = "0")),
                           matrix(stri_rand_strings(n = n^2, length = 4,
                                                    pattern = "[a-zあ-んア-ンA-Z0-9]"), n, n))
colnames(TestData2) <- c("Time", paste0("Word", formatC(1:n, width = 2, flag = "0")))
########

Output Example


I hope this makes your analysis a little easier !!

Copied title and URL