【发布时间】:2025-12-08 19:35:01
【问题描述】:
作为问题,我发现我可以在 sqlite shell 中使用.import,但似乎它在 R 环境中不起作用,有什么建议吗?
【问题讨论】:
作为问题,我发现我可以在 sqlite shell 中使用.import,但似乎它在 R 环境中不起作用,有什么建议吗?
【问题讨论】:
您可以在sqldf 包中使用read.csv.sql。只需一行代码即可读取。假设您要创建一个新数据库 testingdb,然后将文件读入其中,请尝试以下操作:
# create a test file
write.table(iris, "iris.csv", sep = ",", quote = FALSE, row.names = FALSE)
# create an empty database.
# can skip this step if database already exists.
sqldf("attach testingdb as new")
# or: cat(file = "testingdb")
# read into table called iris in the testingdb sqlite database
library(sqldf)
read.csv.sql("iris.csv", sql = "create table main.iris as select * from file",
dbname = "testingdb")
# look at first three lines
sqldf("select * from main.iris limit 3", dbname = "testingdb")
上面使用了使用 RSQLite 的 sqldf。您也可以直接使用 RSQLite。请参阅 RSQLite 中的 ?dbWriteTable。请注意,如果您直接使用 dbWriteTable 来处理行尾可能会出现问题,sqldf 会自动处理(通常)。
如果您的意图是在将文件读入数据库后立即将其读入 R,并且之后您并不真的需要数据库,请参阅:
http://code.google.com/p/sqldf/#Example_13._read.csv.sql_and_read.csv2.sql
【讨论】:
attach 语句创建的 - 不是由前端 sqldf 创建的),因此 sqldf 不会删除它。请注意,sqldf 旨在用于数据帧的临时操作,但如果您处理持久性数据库,那么您可能希望直接使用 RSQLite、RH2 或其他数据库接口包。
library(sqldf) 加载了使用sqldf 命令所需的 sqldf 包。
我倾向于使用 sqldf 包:Quickly reading very large tables as dataframes in R
请记住,在上面的示例中,我将 csv 读入了一个临时 sqlite 数据库。你显然需要改变那一点。
【讨论】: