[R] Problems with looping in R
    Dieter Menne 
    dieter.menne at menne-biomed.de
       
    Wed Feb 10 11:39:05 CET 2010
    
    
  
vikrant wrote:
> 
>  
> my<-function(servername,dbname,dbtable){
> ...
> 	final_set <- NULL
> 	for(b_val in unique_b_vals)	
> 	{
> 		temp1 = subset(init_data,init_data[,3] == b_val,)
> 		temp1 = temp1[sample(dim(temp1)[1], 200),]
> 		if (is.null(final_set))
> 		{
> 			final_set <<- temp1
> 		}
> 		else 
> 			final_set <<- rbind(final_set,temp1)
> 		
> 	}
> }
> 
> When I am doing this directly from the command line and not through this
> function the for loop runs well and gives me the sample data. But when I
> try to put this in a function the loop is failing and does not contain any
> data.I debugged the code init_data contains data but final_set does not
> contain any data. 
> 
Remove all <<-, these are harmful for your health and should be used by
trained neurosurgeons only. Add
final_set 
(think of "return(final_set)")
as the last line of your function, and use the function return in your
calling part.
As an aside: Avoid "select *", use select (primary key) where ... is not
null instead, and do the sampling on the primary keys.
Dieter
-- 
View this message in context: http://n4.nabble.com/Problems-with-looping-in-R-tp1475550p1475596.html
Sent from the R help mailing list archive at Nabble.com.
    
    
More information about the R-help
mailing list