4

I am creating nonsense words given lists of first consonant, vowel, final consonant:

initial_consonants <- c("r", "w", "h", "sp", "st", "sk")
vowels <- c("i", "u", "I", "U", "E", "V", "@")
final_consonants <- c("f", "ts", "rS", "rv", "rl", "Dz", "lts", "bz")

I'd like to get all possible (6*7*8 = 336) nonsense words given this set of first consonants, vowels, and final consonants. I created this function to that:

create_CVC_words <- function(initial_consonant, vowel, final_consonant){
paste(initial_consonant, vowel, final_consonant, sep = "") -> CVC_word
}

But I don't know how to apply it so that all three dimensions are taken into account. outer() gives me the combination of first consonants and vowels with final consonants varied:

outer(initial_consonants, vowels, final_consonants, FUN = create_CVC_words) -> table
table
     [,1]    [,2]    [,3]    [,4]     [,5]    [,6]    [,7]   
[1,] "rif"   "rults" "rIrl"  "rUrS"   "rEf"   "rVlts" "r@rl" 
[2,] "wits"  "wubz"  "wIDz"  "wUrv"   "wEts"  "wVbz"  "w@Dz" 
[3,] "hirS"  "huf"   "hIlts" "hUrl"   "hErS"  "hVf"   "h@lts"
[4,] "spirv" "sputs" "spIbz" "spUDz"  "spErv" "spVts" "sp@bz"
[5,] "stirl" "sturS" "stIf"  "stUlts" "stErl" "stVrS" "st@f" 
[6,] "skiDz" "skurv" "skIts" "skUbz"  "skEDz" "skVrv" "sk@ts"

But what I need is to have all possible combinations, i.e.:

rif rits rirS rirv rirl riDz rilits ribz
ruf ruts rurS ...
.
.
.
wif wits ...

How can I use / adapt my function to do that? I also need to do this for larger nonsensense words, i.e. biyllabic CVCVC, so the number of dimensions I need to be able to take into account is not limited to three.

Edit: just saw the far general question on how to have outer() take n dimensions here: How to generalize outer to n dimensions? but wasn't able to implement the solution given there for my problem.

Community
  • 1
  • 1
Annemarie
  • 689
  • 6
  • 14
  • 28

3 Answers3

3

You could create all different combinations with expand grid:

apply(expand.grid(initial_consonants, vowels, final_consonants), 1, function(x)create_CVC_words(x[1], x[2], x[3]))

Does this do what you want?

user1981275
  • 13,002
  • 8
  • 72
  • 101
3
do.call(paste0, expand.grid(initial_consonants, vowels, final_consonants))
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
3

This method requires more coding but sticks with your original outer meaning it's faster than the other two responses as expand.grid is almost always slower than outer:

ends <- outer(vowels, final_consonants, paste0)
endsL <- lapply(1:nrow(ends), function(i) ends[i, ])
unlist(lapply(endsL, function(x) outer(initial_consonants, x, paste0)))
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519