如何在不考虑顺序的情况下生成所有可能的向量组合? [英] How to generate all possible combinations of vectors without caring for order?

查看:58
本文介绍了如何在不考虑顺序的情况下生成所有可能的向量组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据框中,我有一列包含字符串.假设它看起来像这样:

In a data frame, I have one column containing character strings. Let's say it looks like this:

x <- unique(df[,1])
x
"A" "A" "B" "B" "B" "C"

我想在不关心顺序的情况下将唯一字符串的所有可能组合设为 2 组,所以 A, BB, A 相同code>,我不想得到与 A, A 这样的组合相同的值.到目前为止,我得到了这一点:

I'd like to get all possible combinations of the unique character strings as sets of 2 without caring about their order, so A, B is the same as B, A, and I don't want to get same values as combination like A, A. So far, I got until this point:

comb <- expand.grid(x, x)
comb <- comb[which(comb[,1] != comb[,2]),]

但是这仍然存在以不同顺序排列具有相同字符串组合的行的问题.我该如何摆脱这种情况?

But this still leaves the problem of having rows with the same combination of strings in a different order. How do I get rid of this?

推荐答案

utils 包中有 combn 函数:

t(combn(LETTERS[1:3],2))
#      [,1] [,2]
# [1,] "A"  "B" 
# [2,] "A"  "C" 
# [3,] "B"  "C"

我有点困惑为什么你的 x 有重复的值.

I'm a little confused as to why your x has duplicated values.

这篇关于如何在不考虑顺序的情况下生成所有可能的向量组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆