So, what I want is a dataframe where the combinations of two random vectors are represented on the row. I do not want duplicate combinations like; 1,2;2,1. Just 1 of them. As well as the combination NOT being self-repeating; 1,1.
Right now I got this simple for loop, but it is not ideal;
unique_combos <- function(v1, v2) {
df <- data.frame(matrix(ncol=2))
counter = 0
for (name1 in v1) {
for (name2 in v2) {
if (name1 != name2){
counter = counter + 1
df[counter,] <- c(name1, name2)
}
}
}
return(df)
}
# example usage;
> v1 <- c(1,2,3,4)
> v2 <- c(3,4,5,6)
> unique_combos(v1, v2)
X1 X2
1 1 3
2 1 4
3 1 5
4 1 6
5 2 3
6 2 4
7 2 5
8 2 6
9 3 4
10 3 5
11 3 6
12 4 3
13 4 5
14 4 6
>
Any vectorized way to do this? Preferably aimed towards performance as well. Besides this I wanted to note that the vectors can be any length and will contain random variables.
Edit1 - my function does not work properly!; I don't want the 3-4 4-3 combination.
Edit2 - My final solution by both @Ryan and @Frank (thanks guys!);
unique_combos <- function(v1, v2) {
intermediate <- unique(CJ(v1, v2)[V1 > V2, c("V1", "V2") := .(V2, V1)])
return(intermediate[V1 != V2])
*note; this does use the packages data.table
and plyr
.