r - Applying a function to every combination of elements in a vector -
i apply (custom) function combinations of array. think best explain example:
matrix 1 :
a b c 1 2 3
matrix 2 :
a b c 4 5 6
i following: obtain combinations of matrix 2 , apply function each follows:
matrix 3 :
ab ac bc cb ca ba 4/2 4/3 5/3 6/2 6/1 5/1
where function applied matrix 3 corresponding element of matrix 2 (represented first letter in each column of matrix 3)/the corresponding element of matrix 2 (represented second letter in each column in matrix 3).
please let me know if unclear, feel may not have explained perfectly.
any appreciated!
thanks
mike
the result not in format asked for, can use outer
to create matrix of results 2 input vectors :
x <- c(a=1,b=2,c=3) y <- c(a=4,b=5,c=6) outer(x,y, fun="/")
will give :
b c 0.25 0.2 0.1666667 b 0.50 0.4 0.3333333 c 0.75 0.6 0.5000000
if want vector result, can use :
m <- outer(x,y, fun="/") v <- as.vector(m) names(v) <- as.vector(outer(names(x),names(y),fun="paste0"))
and :
aa ba ca ab bb cb ac 0.2500000 0.5000000 0.7500000 0.2000000 0.4000000 0.6000000 0.1666667 bc cc 0.3333333 0.5000000
Comments
Post a Comment