[R] matrix assembly
Robin Hankin
r.hankin at noc.soton.ac.uk
Wed Nov 16 11:10:27 CET 2005
Hi
I have a function f(k,l) which returns a matrix for integer k and l.
I want to call f(.,.) for each combination of a supplied vector (as
in expand.grid())
and then I want to assemble these matrices into one big one using
k and l to index the position of the submatrices returned by f(k,l).
Toy example follows.
f <- function(k,l){
matrix(k+l , k , l)
}
and I want to call f() with each combination of c(1,3)
for the first argument and c(2,4,5) for the second
and then assemble the resulting matrices.
I can do it piecemeal:
a <- c(1,3)
b <- c(2,4,5)
expand.grid(a,b)
Var1 Var2
1 1 2
2 3 2
3 1 4
4 3 4
5 1 5
6 3 5
cbind(rbind(f(1,2),f(3,2)) , rbind(f(1,4),f(3,4)) , rbind(f(1,5),f
(3,5)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 3 3 5 5 5 5 6 6 6 6 6
[2,] 5 5 7 7 7 7 8 8 8 8 8
[3,] 5 5 7 7 7 7 8 8 8 8 8
[4,] 5 5 7 7 7 7 8 8 8 8 8
[see how the calls to f(. , .) follow the rows of expand.grid(a,b)]
How to do this in a nice vectorized manner?
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
tel 023-8059-7743
More information about the R-help
mailing list