我正在使用 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/