我使用RSQLite访问一个简单的SQLite数据库来返回一组已定义的数据。我希望能够限制查询,以便通过限制分类字段仅返回数据的子集。
我已经编写了一个函数,我希望能够提供在where子句中使用的参数,但是当我以这种方式运行它并将值作为参数时,我不断得到一个'对象' AAPL'发现错误' (其中参数是AAPL)。
通过对我希望在函数中限制的值进行硬编码,它可以正常工作,并且运行f2(5)
将返回前五行' AAPL'
f2 <- function(n, stockName) {
library(RSQLite)
conSQLiteParallel <- dbConnect("SQLite", dbname="stocks.sqlite")
## this sql works fine
sqlcmdParallel <- paste("SELECT stock, gain ",
"FROM stock_gains ",
"WHERE day <=", n, " and stock ='AAPL'", sep="")
resultsHandleParallel <- dbSendQuery(conSQLiteParallel, sqlcmdParallel)
d <- fetch(resultsHandleParallel)
}
results <- f2(5)
但是当我尝试使用stockName变量将值传递给函数时,它给了我
f2 <- function(n, stockName) {
library(RSQLite)
conSQLiteParallel <- dbConnect("SQLite", dbname="stocks.sqlite")
## this sql does not work correctly, but only gives an error
## when running the function
sqlcmdParallel <- paste("SELECT stock, gain ",
"FROM stock_gains ",
"WHERE stock =", stockName, sep="")
resultsHandleParallel <- dbSendQuery(conSQLiteParallel, sqlcmdParallel)
d <- fetch(resultsHandleParallel)
}
results <- f2(5,APPL) - gives the error "Error in paste("SELECT stock, gain FROM stock_gains WHERE stock =", stockName, :
object 'APPL' not found"
results <- f2(5,'APPL') - gives the error "Error in sqliteExecStatement(conn, statement, ...) :
RS-DBI driver: (error in statement: no such column: APPL) "
results <- f2(5,distinctStocks[1,1]) - gives the error "Error in sqliteExecStatement(conn, statement, ...) :
RS-DBI driver: (error in statement: no such column: AAPL) "
任何帮助都会感激不尽,因为我对此感到有些沮丧。
答案 0 :(得分:1)
stockName
应该在引号中:
paste0("SELECT stock, gain FROM stock_gains WHERE day <= ", n,
" and stock = '", stockName, "'")
这也应该有效:
library(gsubfn)
fn$identity("SELECT stock, gain
FROM stock_gains
WHERE day <= $n and stock = '$stockName'")