Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Randomly shuffle letters in words in sentences

I want to randomly disrupt the order of the letters that make up words in sentences. I can do the shuffling for single words, e.g.:

a <- "bach"
sample(unlist(str_split(a, "")), nchar(a))
[1] "h" "a" "b" "c"

but I fail to do it for sentences, e.g.:

b <- "bach composed fugues and cantatas"

What I've tried so far:

split into words:

b1 <- str_split(b, " ")
[[1]]
[1] "bach"     "composed" "fugues"   "and"      "cantatas"

calculate the number of characters per word:

n <- lapply(b1, function(x) nchar(x))
n
[[1]]
[1] 4 8 6 3 8

split words in b1 into single letters:

b2 <- str_split(unlist(str_split(b, " ")), "")
b2
[[1]]
[1] "b" "a" "c" "h"    
[[2]]
[1] "c" "o" "m" "p" "o" "s" "e" "d"    
[[3]]
[1] "f" "u" "g" "u" "e" "s"    
[[4]]
[1] "a" "n" "d"    
[[5]]
[1] "c" "a" "n" "t" "a" "t" "a" "s"

Jumble the letters in each word based on the above:

lapply(b2, function(x) sample(unlist(x), unlist(n), replace = T))
[[1]]
[1] "h" "a" "c" "b"   
[[2]]
[1] "o" "p" "o" "s"   
[[3]]
[1] "g" "s" "s" "u"    
[[4]]
[1] "d" "d" "a" "d"   
[[5]]
[1] "c" "n" "s" "a"

That's obviously not the right result. How can I randomly jumble the sequence of letters in each word in the sentence?

Upvotes: 2

Views: 272

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389047

After b2 you can randomly shuffle character using sample and paste the words back.

paste0(sapply(b2, function(x) paste0(sample(x), collapse = "")), collapse = " ")
#[1] "bhac moodscpe uefusg and tsatnaac"

Note that you don't need to mention the size in sample if you want the output to be of same length as input with replace = FALSE.

Upvotes: 2

Related Questions