一起使用sqldf和RPostgreSQL [英] Using sqldf and RPostgreSQL together

查看:118
本文介绍了一起使用sqldf和RPostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 RPostgreSQL 时,我发现不能以相同的方式使用 sqldf 。例如,如果我加载库并使用以下代码将数据读入数据帧:

When using RPostgreSQL I find that I cannot use sqldf in the same way. For example if I load the library and read in data into a data frame using the following code:

library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, host="localhost", user="postgres", password="xxx", dbname="yyy", port="5436")
rs <- dbSendQuery(con, "select * from table");                           
df<- fetch(rs, n = -1); dbClearResult(rs) 
dbDisconnect(con) 

我知道此表的内容位于数据框 df 。但是,如果我想使用 sqldf 运行SQL命令,我以前会做这样的事情:

I know have the contents of this table in the dataframe df. However if I want to run a SQL command using sqldf I would previously do something like this:

sqldf("SELECT * FROM df WHERE X > 10")

此在收到错误消息后不再起作用:

This no longer works as I get the error message:

Error in postgresqlNewConnection(drv, ...) : 
  RS-DBI driver: (could not connect postgres@localhost on dbname "test"
)
Error in !dbPreExists : invalid argument type

我认为这是操作符错误,但我无法确定应如何向 sqldf 提供哪些参数。

I assume this is operator error on my part, but I can't figure how what arguments to supply to sqldf so that it just focuses on the data frame and does not try to connect to anything else.

推荐答案

在RPostgreSQL中使用sqldf

sqldf 将自动与 test PostgreSQL中的数据库(如果看到已加载RPostgreSQL)。因此,您可以在PostgreSQL中创建一个 test 数据库,然后对该

sqldf will automatically work with the test database in PostgreSQL if it sees that RPostgreSQL is loaded. So you can create a test database in PostgreSQL and then use sqldf with that

使用sqldf,或者,可以指定名称不同的数据库。

or, you can specify the name of a different database.

请参阅: sqldf常见问题12

在RSQLite中使用sqldf

如果您想将sqldf与RSQLite一起使用,而不是与RPostgreSQL一起使用,则可以使用 sqldf drv 参数强制其使用非默认驱动程序。例如

If you want to use sqldf with RSQLite rather than with RPostgreSQL you can use sqldf's drv argument to force it use a non-default driver. e.g.

sqldf("select foo from bar...",drv="SQLite")

或者,您可以使用 sqldf.driver 选项全局设置驱动程序。在R中:

or, you can set the driver globally using the "sqldf.driver" option. From within R:

options(sqldf.driver = "SQLite")

或者,如果您想使用RSQLite,另一种可能性是在使用sqldf并加载之前,先 detach RPostgreSQL

or, another possibility if you wish to use RSQLite is to detach RPostgreSQL before you use sqldf and load it again afterwards.

有关详细信息,请参见?sqldf

See ?sqldf for details.

这篇关于一起使用sqldf和RPostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆