[R] Problems with looping in R

vikrant vikrant.shimpi at tcs.com
Wed Feb 10 10:44:57 CET 2010


Dear R Experts,
This is my R function. 

 
my<-function(servername,dbname,dbtable){
 	library(RODBC)
 	channel<- odbcDriverConnect(paste("driver=SQL Server;server=",servername))
 	init_data<- sqlQuery(channel,paste("select * from",dbname,"..",dbtable))
 	init_data <- subset(init_data,!is.null(init_data[,1]),)
	print(dim(init_data))
	unique_b_vals = unique(init_data[,3])
	print(unique_b_vals)
	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)
		
	}
}

Here What I am doing is connecting to MS sql Server through R and extracting 
the data and init_data contains all my data matrix. After getting all the
data in init_data I want to randomly select data of size say 200. 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. 
The appending is not working when i put this in a function but the same code
works fine without a function
Any solution for this? Please Help
-- 
View this message in context: http://n4.nabble.com/Problems-with-looping-in-R-tp1475550p1475550.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list