[R] Speeding nested loops up

David Winsemius dwinsemius at comcast.net
Thu Aug 18 04:09:47 CEST 2011


On Aug 17, 2011, at 8:14 PM, mark_horo wrote:

> Hi I'm trying to speed my loop up. Any Suggestions?? At the moment  
> it takes a
> few days to run.
>
> THE CODE

We are not surprised.

Rainfall_dataset <- read.table("1km_grid_nzmg.csv", 								 
header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)	
> ---------------------------------------------------------------------------------------------------
> 	for(i in 1:11) {
> 		for (j in 3:12) {
# What is x ???  Where is y dimensioned???
# whatever the answers,     this would be faster --->
                               y[ ,1] <- x[i,j, ]
>
> 			for (k in 1:273107) {					
> # and this is no longer needed in the inner loop  y[k,1] <- x[i,j,k]

> 						print(y)
> 							
> 	# t <- Rainfall_dataset
> 	# print(t)
> 					p<-cbind(t,y)

???? You are just writing out a set of vectors as the first column to  
identical copies of the entire RainfalL_dataset?

> 					#y<-cbind(t,y)   Huh???
> 					#print(y)			
> 			}
> 					# This where you write out array y to a csv file
> 					# Save output as a csv file	
> 					site <- paste("site",i,"-",j)
>
> 	csvfile <- paste(site,sep=".","csv"); print(csvfile)
> 	path<- paste("c:/Data/",csvfile)
> 	print(path)
> 							write.csv(p,file=path, row.names = TRUE)		
> 		}
> 	}
>

To me this looks like a 11*10* 273107 == 30MB set of files with no  
real added information. Surely a database solution must be better.

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list