[R] avoiding loops

Gabor Grothendieck ggrothendieck at myway.com
Sat Jan 29 19:51:01 CET 2005



From:   Frank Samuelson <fws4 at cdrh.fda.gov>
> Along the lines of this thread,
> is there a general apply type function that
> allows me to take one vector at a time from a matrix (or
> row from a data frame) and another vector from another matrix
> and apply them on a general function? Sort of a multidimensional
> mapply, or an 'inner' routine where you can define the
> function (like you can for 'outer'.)
> 
> I've found that I do this regularly in my coding and I usually
> end up using indices (which are pretty fast in R):
> inner<-function(a,b,FUN=function(x,y) sum(x*y))
> sapply(1:nrow(a),function(i) FUN(a[i,],b[,i]))
> 
> Is there existing routine that does this?
> 

inner <- function(a,b,f) {
	f <- match.fun(f)
	apply(b,2,function(x)apply(a,1,function(y)f(x,y)))
}

# e.g. 
inner(matrix(1:4,2), matrix(4:1,2), crossprod)

matrix(1:4,2) %*% matrix(4:1,2) # same




More information about the R-help mailing list