[R] apply with two matrixes
Jason Turner
jasont at indigoindustrial.co.nz
Thu Mar 13 21:25:07 CET 2003
On Wed, Mar 12, 2003 at 02:34:54PM -0700, Katalin Csillery wrote:
> I have a function which does a certain task with two vectors,
> f1 <- function(a,b){body}
>
> I also have a list of matrixes (all with the same dim's), and for each
> column of each matrix in the list I want to use "f1", in such way that
> it gives the vector "a" in the first argument of "f1". The second argument
> of the function "b" also comes form a column of matrix (same dim's as any
> matrix in the list), but that matrix is the same for all matrixes in the
> list.
> I use a separate function with an apply command to accomplish "f1" on each
> column, and than lapply that function over all matrixes in the list.
> The problem is I do not know how tell to apply to use the respective
> columns of the single matrix over all matrixes in the list.
>
> Example (this does not work this way),
> m #original matrix
> l <- list(m1, m2, m3, ...) #list of matrixes
> f1 <- function(a, b){body}
> f2 <- function (mx) apply(mx, 2, f1, b = m)
> lapply(l, f2)
>
> What I want to end up with is a list of list (say lend), where
> length(lend) = length(l)
> length(lend[[any]]) = varies with some properties of the matrixes
>
> My guess is that I sould use tapply, but I could not get it right.
> The problem would be pretty easy with a loop, but efficiency is very
> important, because the objects are huge and functions a computationally
> intense.
<sidenote about loops>
A loop probably wouldn't be as bad as you might think. I'm led to believe
that much of the loop avoidance philosophy in R/S is to help readability,
these days. Once there was an efficiency argument, but those days
are gone, for R at least.
</sidenote about loops>
I think the above doesn't work because by the time apply goes to call
f1 with b=m as an argument, it might not be in an environment where
f1 or m are defined. Do you get an error message to that effect? It's
hard to diagnose from here, using only the above information.
Using *apply, something like this might work.
lend <- lapply(l, function(mx,mb,...) {
f1 <- function(a,b,...) {body}
apply(mx,2,f1,mb,...)
}, m)
Cheers
Jason
--
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz
More information about the R-help
mailing list