gpt4 book ai didi

r - 如何在R中生成对象的排列或组合?

转载 作者:行者123 更新时间:2023-12-03 11:48:17 31 4
gpt4 key购买 nike

如何从r对象生成n对象的序列?我正在寻找一种方法来进行置换或组合,有/无替换,使用明显和不明显的项目(也称为多集)。
这与twelvefold way有关。可以以十二种方式包括“不同”的解决方案,而不包括“非不同”的解决方案。

最佳答案

编辑:我已经更新了答案,以使用更有效的软件包 arrangements

开始使用arrangement

arrangements包含一些有效的生成器和迭代器,用于排列和组合。已经证明arrangements胜过大多数同类的现有软件包。可以找到一些基准here

这是上述问题的答案

# 1) combinations: without replacement: distinct items

combinations(5, 2)

[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 1 5
[5,] 2 3
[6,] 2 4
[7,] 2 5
[8,] 3 4
[9,] 3 5
[10,] 4 5


# 2) combinations: with replacement: distinct items

combinations(5, 2, replace=TRUE)

[,1] [,2]
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 1 4
[5,] 1 5
[6,] 2 2
[7,] 2 3
[8,] 2 4
[9,] 2 5
[10,] 3 3
[11,] 3 4
[12,] 3 5
[13,] 4 4
[14,] 4 5
[15,] 5 5



# 3) combinations: without replacement: non distinct items

combinations(x = c("a", "b", "c"), freq = c(2, 1, 1), k = 2)

[,1] [,2]
[1,] "a" "a"
[2,] "a" "b"
[3,] "a" "c"
[4,] "b" "c"



# 4) combinations: with replacement: non distinct items

combinations(x = c("a", "b", "c"), k = 2, replace = TRUE) # as `freq` does not matter

[,1] [,2]
[1,] "a" "a"
[2,] "a" "b"
[3,] "a" "c"
[4,] "b" "b"
[5,] "b" "c"
[6,] "c" "c"

# 5) permutations: without replacement: distinct items

permutations(5, 2)

[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 1 5
[5,] 2 1
[6,] 2 3
[7,] 2 4
[8,] 2 5
[9,] 3 1
[10,] 3 2
[11,] 3 4
[12,] 3 5
[13,] 4 1
[14,] 4 2
[15,] 4 3
[16,] 4 5
[17,] 5 1
[18,] 5 2
[19,] 5 3
[20,] 5 4



# 6) permutations: with replacement: distinct items

permutations(5, 2, replace = TRUE)

[,1] [,2]
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 1 4
[5,] 1 5
[6,] 2 1
[7,] 2 2
[8,] 2 3
[9,] 2 4
[10,] 2 5
[11,] 3 1
[12,] 3 2
[13,] 3 3
[14,] 3 4
[15,] 3 5
[16,] 4 1
[17,] 4 2
[18,] 4 3
[19,] 4 4
[20,] 4 5
[21,] 5 1
[22,] 5 2
[23,] 5 3
[24,] 5 4
[25,] 5 5


# 7) permutations: without replacement: non distinct items

permutations(x = c("a", "b", "c"), freq = c(2, 1, 1), k = 2)

[,1] [,2]
[1,] "a" "a"
[2,] "a" "b"
[3,] "a" "c"
[4,] "b" "a"
[5,] "b" "c"
[6,] "c" "a"
[7,] "c" "b"



# 8) permutations: with replacement: non distinct items

permutations(x = c("a", "b", "c"), k = 2, replace = TRUE) # as `freq` doesn't matter

[,1] [,2]
[1,] "a" "a"
[2,] "a" "b"
[3,] "a" "c"
[4,] "b" "a"
[5,] "b" "b"
[6,] "b" "c"
[7,] "c" "a"
[8,] "c" "b"
[9,] "c" "c"

与其他软件包比较

与现有软件包相比,使用 arrangements几乎没有优势。
  • 集成框架:您不必为不同的方法使用不同的包。
  • 非常有效。有关某些基准,请参见https://randy3k.github.io/arrangements/articles/benchmark.html
  • 内存效率高,能够生成全部13个!由于矩阵大小的限制,将1到13的排列置换为现有软件包将无法做到这一点。迭代器的getnext()方法允许用户一个接一个地安排。
  • 生成的排列是某些用户可能希望的字典顺序。
  • 关于r - 如何在R中生成对象的排列或组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569176/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com