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 !!

Amazon audibleの登録の紹介

プライム会員限定で2024年7月22日まで3か月無料体験キャンペーン開催中です。無料体験後は月額1,500円で聞き放題です。なお、聞き放題対象外の本はAudible会員であれば非会員価格の30%引きで購入することが可能です。

Amazon audibleはプロのナレーターが朗読した本をアプリで聞くことができるサービスで、オフライン再生も可能です。通勤や作業のお供にAmazon audibleのご登録はいかがでしょうか。

・AmazonのAudible

https://amzn.to/3L4FI5o

Copied title and URL