[R] Passing argument to a function called within another function
Aarti Dahiya
aarti_dahiya at hotmail.com
Tue Jun 27 22:36:00 CEST 2006
#Test at command line
getQuery(name='John')
This should give the result- select * from table_name where name='John'
Instead, it gives- select * from table_name where = ' name = 'John'
The reason is because in function call queryGenerator$generateQuery(passed)
from within getQuery(), passed is a character vector so the function
generateQuery() treats the whole thing as one argument value i.e. as
args[[1]].
What can I do solve this problem? Thanks. I appreciate any help.
File QueryGenerator.R
-------------------------------
#Constructor for QueryGenerator
setConstructorS3("QueryGenerator", function()
{
extend(Object(), "QueryGenerator")
})
# Called when print(object) or object$print is called
setMethodS3("as.character", "QueryGenerator", function(this)
{
paste("This is a QueryGenerator object.")
})
# getData function generates the SQL query
setMethodS3("generateQuery", "QueryGenerator", function(this,...)
{
args <- list(...)
sql <- "select * from table_name where"
for(i in 1:length(args))
{
if(is.numeric(args[[i]]))
{
sql = paste(sql, names(args[i]), "=", args[[i]], collapse = " ")
}
else if(is.character(args[[i]]))
{
sql = paste(sql, names(args[i]), "=", sQuote(args[[i]]), collapse = "
")
}
# If in the current iteration args is not the last argument
# add "and" keyword
if(!identical(i, length(args)))
{
if(identical(names(args[i]),names(args[i + 1])))
sql = paste(sql, "or", collapse = " ")
else
sql = paste(sql, "and", collapse = " ")
}
cat("\nIntermediate Queries\n")
cat(sql)
}
cat("\n\nFinal query\n")
cat(sql)
cat("\n")
return(sql)
})
File getQuery.R
----------------------
getQuery <- function(...)
{
args <- list(...)
#Create the argument to be passed to generateQuery
passed <- sub(",", "", paste(rbind(",", names(args), "=", sQuote(args)),
collapse = " "))
#Create the QueryGenerator Object
queryGenerator <- QueryGenerator()
#Call getData() of DataRetriever class.
results <- queryGenerator$generateQuery(passed)
}
More information about the R-help
mailing list