按顺序生成置换-R
我以前问过以下问题按顺序生成置换-R,r,performance,permutation,R,Performance,Permutation,我以前问过以下问题 这个问题的答案非常有效,只要n相对较小(迭代器是解决问题的好方法。有一个名为arrangements的包,它能够以迭代方式生成置换。注意: library(arrangements) # initialize iterator iperm <- ipermutations(0:1, 3, replace = T) for (i in 1:(2^3)) { print(iperm$getnext()) } [1] 0 0 0 [1] 0 0 1 . .
这个问题的答案非常有效,只要n相对较小(迭代器是解决问题的好方法。有一个名为
arrangements
的包,它能够以迭代方式生成置换。注意:
library(arrangements)
# initialize iterator
iperm <- ipermutations(0:1, 3, replace = T)
for (i in 1:(2^3)) {
print(iperm$getnext())
}
[1] 0 0 0
[1] 0 0 1
.
.
.
[1] 1 1 1
这允许更好的性能,因为下一个排列是由C
中的for循环生成的,而不是R
中的for循环生成的
如果您真的需要提高性能,您可以使用并行
软件包
iperm <- ipermutations(0:1, 40, replace = T)
parallel::mclapply(1:100, function(x) {
myPerms <- iperm$getnext(10000)
# do something
}, mc.cores = parallel::detectCores() - 1)
iperm
010
100
011
library(arrangements)
# initialize iterator
iperm <- ipermutations(0:1, 3, replace = T)
for (i in 1:(2^3)) {
print(iperm$getnext())
}
[1] 0 0 0
[1] 0 0 1
.
.
.
[1] 1 1 1
iperm$getnext(m)
iperm <- ipermutations(0:1, 40, replace = T)
parallel::mclapply(1:100, function(x) {
myPerms <- iperm$getnext(10000)
# do something
}, mc.cores = parallel::detectCores() - 1)