[R] Use apply on a function with multiple argument including a matrix ?

David Winsemius
Fri, 27 May 2011 20:57:01 -0000

On May 27, 2011, at 3:34 PM, sunelav wrote:

> Hello,
>
> I wrote a function that takes a matrix M and several numeric
> parameters as
> arguments. It returns a square matrix (same number of rows than M).
> I need
> to use this function n times (n>1000) with random parameters.

Just one matrix M and many parameters?

>
> I would like to increase the speed

Loops are not necessarily slow in R. Pre-allocation of target object
size and proper use of indexing and vectorisation may add considerably
to efficient execution. In a task of this size (which I would call
"small"), it would appear to be inefficiency in the function that is
the root of your problem.

> of this computation in order to increase
> the size of M  I can use as an input. To do so, I would like to use a
> function of the apply family but I am not sure whether it is
> possible in my
> case. Have you got any idea ?

?mapply

mapply("f", p1, p2, p3, moreArgs=list(M=M) )

But no promises about improving on speed versus a loop.

>
> I initially thought I could create a list containing the vectors of
> the 3
> random parameters and run lapply. However, in this case I don't know
> how to
> put M as another argument for the function.
>
> Thank you very much for your help,
> Cheers,
>
> Sunelav.
>
> To make things clearer; this is the loop I would like to eliminate
>
> # the function
>
> f=function(M,p1,p2,p3) # A matrix and 3 numeric parameters
> {....
> return(SM) } # a square matrix
>
>
> # the Loop
>
> SM=f(M,p1,p2,p3)
>
> for (i in 1:10000)
> { p1=runif(..); p2=runif(..); p3=runif(..)
>   SM=SM+f(M,p1,p2,p3) }
>
>
>
> View this message in context:
http://r.789695.n4.nabble.com/Use-apply-on-a-function-with-multiple-argument-including-a-matrix-tp3556193p3556193.html


David Winsemius, MD
West Hartford, CT