Little useless-useful R functions – Word scrambler
This article is originally published at https://tomaztsql.wordpress.com
This time the simple useless function will generate a scrambled word or will generated a sentence of scrambled words.
Imagine the pangram – “The quick brown fox jumps over the lazy dog“. And that you want the letters in each word to be scrambled or shuffled.
So you have a text:
“This is a successful writing of the Quick brown fox jumps over the lazy dog“
And you get in return the following text:
“sith is a ssclcufseu gntwtrii fo het uikcq brnow xfo spmuj over eht zayl dog“
Little bit eyes boggling
The R function is fairly short:
#helper function full_scramble <- function(s_word) { s_word <- as.character(s_word) i <- sample(1:nchar(s_word)) sep_word <- unlist(strsplit(s_word, "")) paste(sep_word[i], collapse = "") } WordScrambler <- function(text){ Words <- as.list(el(strsplit(Text, " "))) New_text <- paste0(unlist(sapply(1:length(Words), function(x) full_scramble(Words[x]))), collapse = " ") return(tolower(New_text)) }
And you can use the function as:
Text <- "This is a successful writting of the quick brown fox jumps over the lazy dog" WordScrambler(Text)
Getting the results as:
As always, code is available on Github.
Happy R-Coding and stay healthy!
Thanks for visiting r-craft.org
This article is originally published at https://tomaztsql.wordpress.com
Please visit source website for post related comments.