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!
[…] by data_admin [This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page […]
LikeLike
If you leave the first and last letter intact, then the sentences remain largely readable.
This paper contains an experiment: https://www.researchgate.net/publication/7270820_Raeding_Wrods_With_Jubmled_Lettres_There_Is_a_Cost
LikeLike
Thank you Peter. will add a switch to enable this feature. Best, Tomaž
LikeLike
Here’s an alternative to consider:
fun <- function(x) rawToChar(sample(x))
WordScrambler <- function(text) {
w <- charToRaw(text)
words <- cumsum(w == "20")
tolower(paste(tapply(w[w != "20"], words[w != "20"], fun), collapse = " "))
}
Enjoy!
LikeLike
Thank you Ananda for tapply solution.
LikeLike
One liner just for fun
paste(sapply(strsplit(Text,” “)[[1]], function (y) paste0(sapply(sample(nchar(y)),function(x) tolower(substring(y,x,x))),collapse = ”)),collapse = ” “)
LikeLike
[…] Little useless-useful R functions – Word scrambler […]
LikeLike