在data.frame中获取用户指定变量的数据

时间:2013-11-26 14:12:43

标签: r qsqlquery

我昨天问了这个问题并得到了回答,但我不认为他们真的理解我的问题。我需要从数据库中提取数据。但是用户提供了变量列表。我需要我的代码遍历每个请求的变量,拉出与之关联的数据并将其放入data.frame中,以备分析。

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)

1 个答案:

答案 0 :(得分:0)

您认为自己编码的语言是什么?这不是.NET ......

删除此

 for (i in 1:length(variables))
  {
 dataCollection <- sqlQuery(db, 'SELECT table.variables[[i]]
                    FROM table;')
 }

其中'SELECT table.variables[[i]] FROM table;'将始终为循环的所有循环的 SAME ,并且更改为(至少我猜你想要做什么)

 for (i in 1:length(variables))
  {
 dataCollection <- sqlQuery(db, paste0('SELECT table.variables[[', i, ']]
                    FROM table;'))
 }

你说上面的说法不起作用。没有必要继续检查您的代码,修复上述内容然后再回来