创建无意义的单词 - 在R中使用带有三个+维度的outer()

时间:2013-06-06 11:20:30

标签: r word outer-join

我在第一个辅音,元音,最后一个辅音的列表中创建了无意义的单词:

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")

我希望得到所有可能的(6 * 7 * 8 = 336)无意义的单词给出这组辅音,元音和最终辅音。我创建了这个函数:

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

但我不知道如何应用它以便考虑所有三个维度。 outer()给了我第一辅音和元音的组合,最终的辅音有所不同:

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"

但我需要的是拥有所有可能的组合,即:

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

我如何使用/改编我的功能来做到这一点?我还需要对更大的无语单词,即双音节CVCVC这样做,因此我需要考虑的维度数量不限于三个。

编辑:刚刚看到了关于如何让outer()取n个维度的一般性问题:How to generalize outer to n dimensions? 但无法为我的问题实施解决方案。

3 个答案:

答案 0 :(得分:3)

您可以使用expand grid创建所有不同的组合:

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

这样做你想要的吗?

答案 1 :(得分:3)

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

答案 2 :(得分:3)

此方法需要更多编码,但与原始outer相符,这意味着它比其他两个响应更快,因为expand.grid几乎总是比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)))