Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate all possible combinations of vectors without caring for order?

Tags:

r

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"

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?

like image 343
AnjaM Avatar asked Sep 03 '12 09:09

AnjaM


1 Answers

There's the combn function in the utils package:

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

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

like image 141
BenBarnes Avatar answered Sep 28 '22 12:09

BenBarnes