r - 从数字的分区生成排列
问题描述
我将生成一个分区的排列。我使用以下代码生成分区: library(partitions)
x <- c(2,4,6)
parts <- listParts(length(x))
out <- rapply(parts, function(ii) x[ii], how="replace")
并生成
出去
[[1]]
[1] (2,4,6)
[[2]]
[1] (2,6)(4)
[[3]]
[1] (2,4)(6)
[[4]]
[1] (4,6)(2)
[[5]]
[1] (2)(4)(6)
以一个元素为例,[1](2)(4)(6)
我会生成所有可能的排列。我试过:
library(combinat)
permn(x)
但返回元素与输入的形式不同,例如元素
[1](21,33,41,40,39,3,6)(13,37)
返回:
[[1]]
[[1]]$`1`
[1] 21 33 41 40 39 3 6
[[1]]$`2`
[1] 13 37
[[2]]
[[2]]$`2`
[1] 13 37
[[2]]$`1`
[1] 21 33 41 40 39 3 6
几周前我做了类似的问题,但是在生成分区时给出的解决方案会为所有可能的分区生成排列,但是对于效率问题我不能使用它。解决方案就是这样:
library(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)}
解决方案
推荐阅读
- ruby - 将条件语句更改为循环
- php - 添加评论 WP 时查找错误 500 的原因
- regex - 在文本中查找关键字
- python-3.x - 如何将嵌套查询字符串参数从 Amazon API Gateway 传递给 AWS Lambda
- javascript - 如何在 vanillaJS 中使用 localStorage
- amazon-web-services - Redshift 使用 \\ 卸载 SELECT 语句
- xamarin.forms - 如何在 Xamarin.Forms 中检查暗模式
- java - 这些错误信息是什么意思?(Java 摇摆)
- azure - 使用 Azure DevOps,如何将发布管道迁移到代码,类似于构建管道 yml?
- c++ - 如何将双端队列>>向量>>字节迭代到函数