gpt4 book ai didi

r - R中没有重复的组合

转载 作者:行者123 更新时间:2023-12-04 10:44:52 25 4
gpt4 key购买 nike

我正在尝试获取变量元素的长度为 3 的所有可能组合。虽然它部分与 combn() 一起工作,但我并没有完全得到我正在寻找的输出。这是我的例子

x <- c("a","b","c","d","e")
t(combn(c(x,x), 3))

我得到的输出看起来像这样
       [,1] [,2] [,3]
[1,] "a" "b" "c"
[2,] "a" "b" "d"
[3,] "a" "b" "e"

出于两个原因,我对这个命令并不满意。我想得到一个输出,上面写着“a+b+c”“a+b+b”......,不幸的是我无法使用 paste() 或其他东西来编辑输出。

我也期待每组字母的一个组合,即我要么得到“a+b+c”或“b+a+c”,但不能同时得到两者。

最佳答案

尝试类似:

x <- c("a","b","c","d","e")
d1 <- combn(x,3) # All combinations

d1

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

nrow(unique(t(d1))) == nrow(t(d1))
# [1] TRUE

d2 <- expand.grid(x,x,x) # All permutations

d2

# Var1 Var2 Var3
# 1 a a a
# 2 b a a
# 3 c a a
# 4 d a a
# 5 e a a
# 6 a b a
# 7 b b a
# 8 c b a
# 9 d b a
# ...

nrow(unique(d2)) == nrow(d2)
# [1] TRUE

关于r - R中没有重复的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21339202/

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