[R] a question regarding apply

Thomas Lumley tlumley at u.washington.edu
Thu Jun 3 17:43:46 CEST 2004

On Thu, 3 Jun 2004, Rajarshi Guha wrote:

> Hi,
>   I have a matrix, m, over whose rows I want to apply a function. I also
> have a vector, r, whose length is equal to the rows of m.
> The obvious way is:
> result <- apply( m, c(1), fun )
> However the function call requires the row from m and the corresponding
> element of r.
> So, I want to pass m[i,] and r[i] to the function.
> Currently I use a loop. But can this be modified to use apply (or
> related functions)?

One way is to stick the vector onto the matrix

  apply(cbind(r,m), 1, function(x) fun(mi=x[-1],ri=x[1]))

Incidentally, there's never any point in writing c(1)
> identical(c(1),1)
[1] TRUE


More information about the R-help mailing list