用列表R的重复计算所有排列

时间:2018-11-06 21:00:22

标签: r list vector permutation

我有以下向量out列表:

[[1]]
[1] (1,5)(3)(4)(6)

[[2]]
[1] (3,6)(1)(4)(5)

[[3]]
[1] (3,4)(1)(5)(6)

[[4]]
[1] (3,5)(1)(4)(6)

[[5]]
[1] (4,6)(1)(3)(5)

[[5]]
[1] (4,5)(1)(3)(6)

[[6]]
[1] (5,6)(1)(3)(4)   

以一个元素为例,例如out[[5]] (4,6)(1)(3)(5),我将以所有可能的顺序生成元素的所有排列,例如:

{(4,6)(3)(1)(5)},{(3)(4,6)(5)(1)}...

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

test <- list(list(1,5),3,4,6)
combn(test,2)
> combn(test,2)
     [,1]   [,2]   [,3]   [,4] [,5] [,6]
[1,] List,2 List,2 List,2 3    3    4   
[2,] 3      4      6      4    6    6   

这将为您提供列表中2个元素的所有可能组合。如果要对主列表的每个元素执行此操作,则可以在其上使用forlapply

尝试:

lapply(out, function(x) combn(x,2))

答案 1 :(得分:1)

gtools软件包如何

out <- list(
 c(1.5,3,4,6),
 c(3.6,1,4,5),
 c(3.4,1,5,6),
 c(3.5,1,4,6),
 c(4.6,1,3,5),
 c(4.5,1,3,6),
 c(5.6,1,3,4))


require(gtools)

allPerm <- function(x){

  return(permutations(length(x), length(x), x))
}

答案 2 :(得分:1)

我认为这是OP所需要的:

out <- list(c("(1,5)","(3)","(4)","(6)"), c("(3,6)","(1)","(4)","(5)"), 
            c("(3,4)","(1)","(5)","(6)"),c("(3,5)","(1)","(4)","(6)"), 
            c("(4,6)","(1)","(3)","(5)"), c("(4,5)","(1)","(3)","(6)"), 
            c("(5,6)","(1)","(3)","(4)"))

library(RcppAlgos)
myPerms <- lapply(out, function(x) {
    unlist(permuteGeneral(x, length(x), FUN = function(y) {
        paste0(c("{", y, "}"), collapse = "")
    }))
})

我们使用permuteGeneral中的RcppAlgos(我是作者),因为我们可以利用FUN参数传递自定义函数,该自定义函数将应用于每个排列(即{{1 }}。

这是第5个元素的输出:

paste0(c("{", y, "}"), collapse = "")

如果您确实想要重复排列,只需在myPerms[[5]] [1] "{(4,6)(1)(3)(5)}" "{(4,6)(1)(5)(3)}" "{(4,6)(3)(1)(5)}" [4] "{(4,6)(3)(5)(1)}" "{(4,6)(5)(1)(3)}" "{(4,6)(5)(3)(1)}" [7] "{(1)(4,6)(3)(5)}" "{(1)(4,6)(5)(3)}" "{(1)(3)(4,6)(5)}" [10] "{(1)(3)(5)(4,6)}" "{(1)(5)(4,6)(3)}" "{(1)(5)(3)(4,6)}" [13] "{(3)(4,6)(1)(5)}" "{(3)(4,6)(5)(1)}" "{(3)(1)(4,6)(5)}" [16] "{(3)(1)(5)(4,6)}" "{(3)(5)(4,6)(1)}" "{(3)(5)(1)(4,6)}" [19] "{(5)(4,6)(1)(3)}" "{(5)(4,6)(3)(1)}" "{(5)(1)(4,6)(3)}" [22] "{(5)(1)(3)(4,6)}" "{(5)(3)(4,6)(1)}" "{(5)(3)(1)(4,6)}" 中设置repetition = TRUE。当然,如果您想要更有用的输出,我们可以完全删除自定义permuteGeneral

更新

在详细了解OP如何从上面获得FUN之后,我们可以更好地解决该问题。首先,我们发现OP使用out库中的listParts。查看源代码,我们有:

partitions

我们可以更改它以获得所有排列:

listParts
function (x) 
{
    f <- function(pp) {
        out <- split(seq_along(pp), pp)
        class(out) <- c(class(out), "equivalence")
        out
    }
    apply(setparts(x), 2, f)
}
<bytecode: 0x10d7b09f8>
<environment: namespace:partitions>

我们注意到我们违背permListParts <- function (x) { f <- function(pp) { out <- split(seq_along(pp), pp) myPerms <- perms(length(out)) apply(myPerms, 2, function(x) { temp <- out[x] class(temp) <- c(class(temp), "equivalence") temp }) } apply(setparts(x), 2, f) } ...引用文档的意图:

  

“请注意,(12)(3)(4)是与例如(3)(4)(21)相同的分区,因为等价关系相同。”

哦,好吧...这是长度为3的排列的输出:

listParts