Creating meaningless words - using external () with three + dimensions in R

I create meaningless words, given the lists of the first consonant, the vowel, the 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 would like to get all the possible (6 * 7 * 8 = 336) meaningless words given this set of first consonants, vowels, and final consonants. I created this function for this:

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

But I do not know how to apply it so that all three dimensions are taken into account. external () gives me a combination of the first consonants and vowels with the final consonants:

 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 I need 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 for this? I also need to do this for big, meaningless words, i.e. bilillic CVCVC, so the number of dimensions I need to consider is not limited to three.

Edit: I just looked at a general general question about how to have external () values ​​for n dimensions: How to generalize external dimensions to n? but could not implement the solution given there for my problem.

+4
source share
3 answers

You can create all the 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 it do what you want?

+3
source
 do.call(paste0, expand.grid(initial_consonants, vowels, final_consonants)) 
+3
source

This method requires more encodings, but has its own outer , which means it is faster than the other two answers, because expand.grid 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))) 
+3
source

Source: https://habr.com/ru/post/1484811/


All Articles