[R] avoiding loops

Frank Samuelson fws4 at cdrh.fda.gov
Sat Jan 29 18:13:51 CET 2005


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?

Thanks.

-Frank


Liaw, Andy wrote:
> Doesn't this work?
> 
> 
>>d1 <- data.frame(x=rnorm(100), y=rnorm(100), z=rnorm(100))
>>d2 <- data.frame(x=rnorm(100), y=rnorm(100), z=rnorm(100))
>>dist.12 <- sqrt(rowSums((d1 - d2)^2))
> 
> 
> Andy
> 
> 
>>From: dax42
>>
>>Hi again,
>>
>>thanks a lot for the quick answer. I just forgot the comma, always 
>>these stupid mistakes...
>>
>>Anyways, as I said before, I have two data.frames containing 
>>about 1000 
>>rows and I would like to avoid looping through all of them...
>>
>>In each data.frame are coordinates (x,y,z), so every row is 
>>giving the 
>>information on one single point.
>>I would like to calculate the distance from each point in the 
>>one frame 
>>to every point in the second...
>>But how to do this without loops, how to do it quickly? I would 
>>appreciate it very much, if someone would introduce me to the 
>>high art 
>>of R - avoiding loops :-).
>>
>>Cheers, Dax.
>>
>>______________________________________________
>>R-help at stat.math.ethz.ch mailing list
>>https://stat.ethz.ch/mailman/listinfo/r-help
>>PLEASE do read the posting guide! 
>>http://www.R-project.org/posting-guide.html
>>
>>
> 
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list