[R] Help with Nested loop - very slow, can I use an apply?

Nikhil Kaza nikhil.list at gmail.com
Tue Dec 8 07:04:54 CET 2009


 From an old post by Gabor
http://tolstoy.newcastle.edu.au/R/help/04/01/0147.html

   
apply 
(outer 
(landmark_c,t(store_c),"-"),c(1,4),function(x)sqrt(sum(diag(x*x))))

On 7 Dec 2009, at 10:58PM, dolar wrote:

>
> Hi there
>
> I have two tables, with longitudinal and latitudinal coordinates.  
> what I
> want is a cross table between each coordinate, to find the distance  
> between
> each building and different landmarks
>
>
> I currently have this nested loop which is fine for when i have 10  
> stores of
> interest, against 200 other landmarks and uses pythagarus to find the
> distance
>
>
> for(i in 1:nrow(store_c)){
> 	landmark_store_cross_tab$foo=landmark_c$landmark_name
> 	for (j in 1:nrow(landmark_c)){
> 	landmark_store_cross_tab[j,i+1]=sqrt((landmark_c$x[j]-store_c$x[i])^2
> 		+(landmark_c$y[j]-store_c$y[i])^2)/1000
> }
> names(landmark_store_cross_tab)[i+1]=store_c$store_name[i]
> }
>
> can someone suggest how I can make this faster?
>
>
> I am hoping to use one of the apply functions
>
> Thanks
>
> -- 
> View this message in context: http://n4.nabble.com/Help-with-Nested-loop-very-slow-can-I-use-an-apply-tp954979p954979.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list