I asked this question yesterday and it was answered but I don't think they really understood my question. I need to extract data from a database. But the user provides the list of variables. I need my code to loop through each requested variable, pull the data associated with it and drop it in a data.frame, ready for analysis.
f.extractVariables<-
structure(function
(dbPath,dbName,table,variables
){
# LOAD LIBRARIES
require(RODBC)
require(xlsx)
setwd(dbPath)
db <- odbcConnectAccess2007(dbName)
#This was my idea on how to loop through the variable list but it won't run
for (i in 1:length(variables))
{
dataCollection <- sqlQuery(db, 'SELECT table.variables[[i]]
FROM table;')
}
#This piece was the solution I was given which runs but all it does is parrot back
#the variable list it doesn't retrieve anything.
variables=paste(variables,collapse=",")
query<-paste(paste("SELECT",variables),
"FROM table",sep='\n')
cat(query)
odbcClose(db)
}
)
#And the user provided input looks something like this. I can change the way the
#variable list comes in to make it easier.
dbPath = 'z:/sites/'
dbName = 'oysterSites.accdb'
table = 'tblDataSiteOysterSamplingPlan'
variables= 'nwLon,nwLat,neLon,neLat'
f.extractVariables(dbPath,dbName,table,variables)