gpt4 book ai didi

r - 使用RSQLite的R中分类变量的where子句

转载 作者:行者123 更新时间:2023-12-03 17:58:23 27 4
gpt4 key购买 nike

我正在使用RSQLite访问简单的SQLite数据库以返回定义的数据集。我希望能够限制查询,以便通过限制类别字段仅返回数据的子集。

我编写了一个函数,希望能够提供在where子句中使用的参数,但是当我以值作为参数运行该函数时,我不断收到“对象'AAPL'发现错误” (其中参数为AAPL)。

通过硬编码要在函数中限制的值,它可以正常工作,运行f2(5)将返回'AAPL'的前5行

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) "


如有任何帮助,我们将不胜感激,不胜感激。

最佳答案

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'")

关于r - 使用RSQLite的R中分类变量的where子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848833/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com