[R] Help on R functions

Duncan Murdoch murdoch at stats.uwo.ca
Tue Feb 9 15:37:44 CET 2010


On 09/02/2010 7:10 AM, vikrant wrote:
> Dear R Experts,
> I have written a following function :-
> 
> myfunction<- function(servername,dbname,dbtablename){
> library(RODBC)
> channel <- odbcDriverConnect("driver=SQL Server;server=servername")
> initdata<- sqlQuery(channel,paste("select * from  dbname ..  dbtablename"))
> return(dim(initdata))
> }
> I have written this function which has input  parameters like servername
> ,dbname and dbtable to connect to Ms SQL server 2005 and get data from the
> table.
> Now when I run this function using the following command
> 
> myfunction("01wh155073","test_DB","test_vikrant")
> 
> 
> The variable initdata should contain all the data. But it does not contain
> any data and dim(initdata)) is NULL.
> 
> I dont know how to pass the strings as parameters  in the function. Do I
> have done this correctly?

No.  "driver=SQL Server;server=servername" is a literal string.  If you 
want to replace servername with the contents of the servername argument, use

paste("driver=SQL Server;server=", servername, sep="")

and similarly for your query.

Duncan Murdoch

> 
> If I run the same commands directly from the command line I get the expected
> data.
> 
> library(RODBC)
> channel <- odbcDriverConnect("driver=SQL Server;server=01wh155073")
> initdata<- sqlQuery(channel,paste("select * from  test_DB .. 
> test_vikrant"))
> dim(initdata)
> 
> Then the initdata contains the data in the table "test_vikrant". My question
> is there a way to write above in a function which contains the above
> parameters.
> Please Help me...



More information about the R-help mailing list