[R] matrix assembly

Gabor Grothendieck ggrothendieck at gmail.com
Wed Nov 16 13:27:15 CET 2005


On 11/16/05, Robin Hankin <r.hankin at noc.soton.ac.uk> wrote:
> 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?
>

Replacing your example with the appropriate do.call and lapply
calls gives this:

do.call("cbind", lapply(b, function(x) do.call("rbind", lapply(a, f, l = x))))

or one can do the cbind in the inner loop and the rbind in the outer
giving the same result:

 do.call("rbind", lapply(a, function(x) do.call("cbind", lapply(b, f, k = x))))




More information about the R-help mailing list