I would like to apply a certain (custom) function to all combinations of an array. I think its best to explain with an example:
Matrix 1 :
A B C
1 2 3
Matrix 2 :
A B C
4 5 6
I would like to do the following: obtain all the combinations of Matrix two and apply a function to each as follows:
Matrix 3 :
AB AC BC CB CA BA
4/2 4/3 5/3 6/2 6/1 5/1
Where the function applied to Matrix 3 is the corresponding element of Matrix 2 (represented by the first letter in each column of Matrix 3)/the corresponding element of Matrix 2 (represented by the second letter in each column in Matrix 3).
Please let me know if anything is unclear, I feel that I may not have explained perfectly.
Any help would be greatly appreciated!
Thanks
Mike
This can be done simply if you install
gtools
and use thepermutations
function.The
mapply
function is a pretty magical built inR
function. It's worth while getting the know the entire family of*apply
functions.The output is in
comboList
, which is as follows:The result is not exactly in the format you asked for, but you can use
outer
to create a matrix of results from your two input vectors :Will give :
If you really want a vector as result, you can use :
And then get :