Little useless-useful R functions – Word scrambler

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This time the simple useless function will generate a scrambled word or will generated a sentence of scrambled words.

Scrambled word

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!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)