[英]RODBC join data frame to table in sqlQuery
I've been using RODBC to connect to a DB2 database at work, and thus far everything works well. 我一直在使用RODBC连接到工作中的DB2数据库,到目前为止一切运行良好。 I can pull tables through sqlQuery, and join tables within the database before getting them back as a data frame.
我可以通过sqlQuery拉表,并在将数据库作为数据框返回之前连接数据库中的表。 However, I often sped up the process in SAS by grabbing and manipulating tables, then joining them back to the database.
但是,我经常通过抓取和操作表,然后将它们连接回数据库来加速SAS中的过程。 When I try to do this in R, I'm having issues.
当我尝试在R中执行此操作时,我遇到了问题。 I'd like it to go something like this.
我希望它能像这样。
library(RODBC)
channel <- odbcConnect(database stuff)
dataframe <- sqlQuery(channel, query)
.
.
manipulate data frame
.
.
dataframe <- sqlQuery(channel,
"select * from dataframe as a INNER JOIN schema.table1 as b ON a.id=b.id")
The problem is that R doesn't recognize "dataframe". 问题是R不识别“数据帧”。 I think it has something to do with the "schema.dataframe" part, as I'm not sure what kind of "schema" the workspace would have.
我认为它与“schema.dataframe”部分有关,因为我不确定工作空间会有什么样的“模式”。 Is there a way to join a data frame to a table in a database in sqlQuery?
有没有办法将数据框连接到sqlQuery中的数据库中的表? Or can I somehow make the data frame a temporary table and join it from there?
或者我可以以某种方式使数据框成为临时表并从那里加入它?
You can either save dataframe as a table to your database with 您可以将数据帧作为表保存到数据库中
sqlSave(channel, dataframe)
(see ?sqlSave for the options) and then do your query. (请参阅?sqlSave了解选项),然后执行查询。 Assuming that channel points to "schema":
假设该通道指向“架构”:
dataframe <- sqlQuery(channel,
"select * from schema.dataframe as a INNER JOIN schema.table1 as b ON a.id=b.id")
Or you can use data.table() and do the join in R: 或者你可以使用data.table()并在R中进行连接:
library(data.table)
dataframe <- data.table(dataframe)
setkey(dataframe, id)
table1 <- data.table(sqlQuery(channel,
"select * from schema.table1")
setkey(table1, id)
dataframe <- dataframe[table1, nomatch=0]
In both cases you would end up with a "auxiliary" object: schema.dataframe in the first case in your db, and table1 in R in the second case. 在这两种情况下,您最终会得到一个“辅助”对象:数据库中第一种情况下的schema.dataframe和第二种情况下R中的table1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.