R sqldf - 循环内部/外部的索引

标签 r sqldf

我正在使用 sqldf 函数重复地将表的子集与其自身连接起来。重复过程发生在 for 循环内。我读过添加索引可以提高这些连接的性能 here

我的问题是 - 如果我在循环中重复执行此操作,这是否意味着我必须在每次循环执行时重新创建索引,或者是否有办法让索引“保留”在循环之外但可以使用在循环内?

换句话说,我只看过这个版本:

for(i in 1:10){
   df1 <- sqldf(c('create index...','select * from table1'))
}

有没有办法做这样的事情:

df1 <- sqldf('create index...') # create index outside of loop

for(i in 1:10){
   df2 <- sqldf('select * from t1 left join t2 on t1.col1 = t2.col1')
}

编辑:

> sqldf() 
NULL
> 
> sqldf("create index idx on iris(Species)") ## 
data frame with 0 columns and 0 rows
> sqldf("select count(*) from main.iris where Species = 'virginica'") ##
Error in rsqlite_send_query(conn@ptr, statement) : 
  no such table: main.iris
> sqldf("select count(*) from main.iris where Species <> 'virginica'") ##
Error in rsqlite_send_query(conn@ptr, statement) : 
  no such table: main.iris
> 
> sqldf()
<SQLiteConnection>
  Path: :memory:
  Extensions: TRUE
> 

EDIT_2:

> sqldf() 
NULL
> # close an old connection if it exists
>    if (!is.null(getOption("sqldf.connection"))) sqldf()
> sqldf() 
<SQLiteConnection>
  Path: :memory:
  Extensions: TRUE
> sqldf("create index idx on iris(Species)") ## 
data frame with 0 columns and 0 rows
> sqldf("select count(*) from main.iris where Species = 'virginica'") ##
  count(*)
1       50
> sqldf("select count(*) from main.iris where Species <> 'virginica'") ##
  count(*)
1      100
> sqldf() 
NULL

最佳答案

sqldf 的无参数形式可用于打开和关闭连接,以便中间 sqldf 语句都可以使用同一连接。

注意,我们可以通过将表x引用为main.x来引用已经上传的表的版本;否则,每个sqldf将尝试再次上传。您还可以考虑将 verbose = TRUE 参数添加到标记为 ## 的语句中,以查看发生了什么。

library(sqldf)

sqldf() 

sqldf("create index idx on iris(Species)") ## 
sqldf("select count(*) from main.iris where Species = 'virginica'") ##
sqldf("select count(*) from main.iris where Species <> 'virginica'") ##

sqldf()

sqldf github home page 上有一些示例.

另一种可能性是直接使用 RSQLite。

另请注意,您可以生成 SQL 字符串向量并将整个向量传递给 sqldf:sqldf(v)

另一种可能性是使用 SQLite 递归公用表表达式。谷歌了解更多信息。

请注意,除了 select 之外的语句(例如 create)会在 RSQLite 2.0 下导致警告,但仍然会给出正确的结果,因此要么忽略警告,要么使用更早的版本RSQLite 版本。

关于R sqldf - 循环内部/外部的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47145260/

相关文章:

r - ggplot2不知道如何处理 react 类的数据

r - 从大数据帧中采样小数据帧

r - 如何在 R SQLDF 中聚合字符串?

r - 如何使用sqldf获取日期?

r - 如何从包 map 更改map.scale的线宽?

R - geom_line() 将点转换为垂直线

r - 为每一行查找最接近的匹配项并根据条件求和

r - sqldf 和 POSIXct

r - 声明一个用户定义的分布

r - 如何在 SQLite 数据库中存储 R 对象(列表)?