Say I have two vectors
upVariables<-c("up1", "up2", "up3", "up4", "up5")
downVariables<-c("down1", "down2", "down3", "down4", "down5")
Each of these will be used to look up an number in another vectors. I'm looking to find all possible sets of two ratios (all possible sets of four variables, two from each vector), where the numerator is always from upVariables, the demnominator is always from downVariables and final set doesn't use the same variable twice.
I've got as far as
upCombos<-combn(upVariables,2)
downCombos<-combn(downVariables,2)
combos<-arrange(expand.grid(upCombos=upCombos[,1],downCombos=downCombos[,1]),upCombos)
I'm only using the first possible combination here, to illustrate, but I'd want to iterate over all possible combinations. This gives me:
> combos
upCombos downCombos
1 up1 down1
2 up1 down2
3 up2 down1
4 up2 down2
What I'd like to produce from this though is two sets, something like:
> combos[1]
upCombos downCombos
1 up1 down1
2 up2 down2
and
> combos[2]
upCombos downCombos
1 up1 down2
2 up2 down1
So that in each case, each value from upCombos is used only once and each value from downCombos is used only once. Does that make sense? Any ideas on how one goes about this?
Ideally I'd like to then be able to generalize to sets of 3 sampled from the original vectors rather than sets of 2, but I'll be happy to get sets of 2 working for now.
** Edit So Jota has provided a solution which provides the arrangements within any group of 4 variables (2 from upVariables, 2 from downVariables). I'm still failing to see how I iterate over all possible sets of 4 variables though. The nearest I've got is to sit Jota's suggestion inside two for loops (spot the not-yet-R-programmer). This this returns many fewer combinations than there should be.
n<-2
offset<-n-1
for (i in 1:(length(upVariable)-offset)){
for (j in 1:(length(downVariables)-offset)){
combos <- expand.grid(upVariables[i:(i+offset)], downVariables[j:(j+offset)])
combos <- combos[with(combos, order(Var1)), ] # use dplyr::arrange if you prefer
mat <- matrix(1:n^2, byrow = TRUE, nrow = n)
for(j in 2:nrow(mat) ) mat[j, ] <- mat[j, c(j:ncol(mat), 1:(j - 1))]
pairs<-(split(combos[c(mat), ], rep(1:n, each = n)))
collapsed<-sapply(lapply(pairs, apply, 1, paste, collapse = '_'), paste, collapse = '-')
ratioGroups<-c(ratioGroups,collapsed)
}
}
This returns only 16 sets of variables (each with 2 combinations, so 32 in all). With 5 variables in each set though, there's many many more possibilities.