【问题标题】:Error in as.character(query) : cannot coerce type 'closure' to vector of type 'character'as.character(query) 中的错误:无法将“闭包”类型强制转换为“字符”类型的向量
【发布时间】:2021-02-04 15:47:50
【问题描述】:

我试图从 oracle 数据库中加载一些数据,在此过程中,每一行代码都很好,直到我尝试运行最后一行: df<- sqlQuery(sql_connection,sql_statement,stringsAsFactors=0), 标题出现错误。

所以这是我的代码的基本结构:

require(RODBC)
require(lubridate)
require(stringr)
require(dplyr)
require(tidyr)

#server for N2 purge attribute
target <- "xxxx"
user   <- "xxxx"
pass   <- "xxxx"


#print("Working on lot history...")


sql_string <- paste0("select
xxxx
from
xxxx
where
xxxx

")

sql_statement <- sprintf

#sql_statement <- sprintf(sql_string, BackDate, DidList[m])
sql_connection <- odbcConnect(dsn = target, uid = user, pwd = pass,believeNRows=FALSE)

df<- sqlQuery(sql_connection,sql_statement,stringsAsFactors=0)

由于我是 R 新手,我觉得我无法判断错误的原因在哪里。如果有人可以帮助我解决这个问题,我将不胜感激。

【问题讨论】:

  • 你用你定义为sql_statement &lt;- sprintfsql_statement调用sqlQuery。因此sql_statement 不是一个字符而是一个函数,而是一个所谓的closure

标签: sql r


【解决方案1】:

在这一行中,您将基本函数sprintf 分配给sql_statement

sql_statement <- sprintf

然后将其作为第二个参数 (query) 传递给 sqlQuery()

df<- sqlQuery(sql_connection,sql_statement,stringsAsFactors=0)

该函数要求 query 是一个字符,因此您会收到错误,即 R 无法将“闭包”(本质上是 another name for a function)强制转换为字符。

我假设您试图模仿这条被注释掉的行:

#sql_statement <- sprintf(sql_string, BackDate, DidList[m])

但如果您只想运行刚刚编写的查询,则没有必要。因此,如果我们只是整理您的代码,以便将 sql_string 直接传递给 sqlQuery(),它应该可以按预期工作,尽管我 can't actually test it 因为我们无权访问您的数据库:

require(RODBC)
require(lubridate)
require(stringr)
require(dplyr)
require(tidyr)

#server for N2 purge attribute
target <- "xxxx"
user   <- "xxxx"
pass   <- "xxxx"

#print("Working on lot history...")

sql_string <- paste0("select
xxxx
from
xxxx
where
xxxx
")

sql_connection <- odbcConnect(dsn = target, uid = user, pwd = pass,believeNRows=FALSE)
df<- sqlQuery(sql_connection,sql_string,stringsAsFactors=0)

【讨论】:

  • 感谢您的精彩解释和快速修复。我在我的数据库上对其进行了测试,效果非常好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2014-07-13
  • 1970-01-01
相关资源
最近更新 更多