[R] when to use which apply function?

David Winsemius dwinsemius at comcast.net
Tue Mar 26 23:53:07 CET 2013


On Mar 26, 2013, at 2:51 PM, C W wrote:

> Dear list,
> 
> I am a little confused as to when to use apply, sapply, tapply, vapply,
> replicate.  I've encountered this several times,
> This is time, this is what I am working on,
> 
> mat <- matrix(c(seq(from=1, to=10), rnorm(10)), ncol=2)
> 
> a=1; b=5
> 
> newfun <- function(x, y, a, b)
> 
> {
> 
> x*y+a+b
> 
> }
> 
> sapply(i=1:10, newfun(x=mat[i, 1], y=mat[i, 2], a=a, b=b))
> 
> Error in match.fun(FUN) : argument "FUN" is missing, with no default
> 
> I want to use ith row of mat, evaluate newfun().  Am I making a parameter
> mistake,

There is nothing that would naturally "catch" the values. After they are evaluated sequentially by `sapply` the values 1:10 no longer are named "i" and so don't naturally fall into the slots you thought you had constructed for them. By constructing an anonymous function with any formal argument name (as already demonstrated by another poster)  you could get to use positional matching.

> or should I use a different apply function?

Yes, "some other function" since all those operations are vectorized, this could be more easily done with:

 mat[ ,1]*mat[ ,2]+a+b   # and no need for a loop, right?

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list