如何从矩阵生成所有组合并为每个可能的结果分配唯一值?

时间:2018-10-30 04:27:06

标签: r

假设我有一个矩阵

mat1<-matrix(c('b','c','q','a','z','d','t','o','p'),nrow=3,ncol=3)

如何生成从左到右,从右到左,从上到下和从下到上的所有可能组合的列表?说“ bc”,“ bcq”,“ qcb”等。另外,我将根据单词的位置为每个元素分配一个唯一的元素。例如,“ bc”对应于“ 1112”,而“ bcq”对应于“ 1113”,“ qcb”对应于“ 1311”。

1 个答案:

答案 0 :(得分:0)

尝试一下:

perms <- function(vec) {
  f <- function(v0) unlist(sapply(seq_along(v0)[-1], function(i) {
    apply(combn(v0, i), 2, paste0, collapse="")
  }))
  c(vec, f(vec), f(rev(vec)))
}

unique(c(sapply(1:2, function(i) apply(m, i, perms))))
#  [1] "b"   "a"   "t"   "ba"  "bt"  "at"  "bat" "ta"  "tb"  "ab"  "tab" "c"  
# [13] "z"   "o"   "cz"  "co"  "zo"  "czo" "oz"  "oc"  "zc"  "ozc" "q"   "d"  
# [25] "p"   "qd"  "qp"  "dp"  "qdp" "pd"  "pq"  "dq"  "pdq" "bc"  "bq"  "cq" 
# [37] "bcq" "qc"  "qb"  "cb"  "qcb" "az"  "ad"  "zd"  "azd" "dz"  "da"  "za" 
# [49] "dza" "to"  "tp"  "op"  "top" "po"  "pt"  "ot"  "pot"

这是它的工作方式。

apply取一个矩阵(m),一个轴(1是“行”,2是“列”)和一个函数({{1} }):

perms

它对输出进行转置(叹气,这是R的事情),因此(来自apply(m, 1, perms) # [,1] [,2] [,3] # [1,] "b" "c" "q" # [2,] "a" "z" "d" # [3,] "t" "o" "p" # [4,] "ba" "cz" "qd" # [5,] "bt" "co" "qp" # [6,] "at" "zo" "dp" # [7,] "bat" "czo" "qdp" # [8,] "ta" "oz" "pd" # [9,] "tb" "oc" "pq" # [10,] "ab" "zc" "dq" # [11,] "tab" "ozc" "pdq" 的每一行都作为一列返回。我们想在行和列上都运行此功能,所以我们也可以这样做

1

通过使用apply(m, 2, perms) 遍历给定sapply的轴,我感到很棘手(事后看来,很不幸)。以下两个是足够的(如果不是精确的结构,内容也是如此):

apply

也许这只是混淆事物...

最后一部分是c(apply(m,1,perms), apply(m,2,perms)) sapply(1:2, function(i) apply(m, 1, perms)) ,它只取出重复项。