我发现在sqlite shell中可以使用.import
命令,但在R环境中好像无法使用,有什么建议吗?
您可以使用sqldf
包中的read.csv.sql
函数。只需一行代码即可完成读取。假设您想创建一个新的数据库testingdb,然后将文件读入其中,请尝试以下代码:
read.csv.sql("filename.csv", sql = paste("CREATE TABLE my_table", "SELECT * FROM file", sep = "\n"), dbname = "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")
以上使用了 sqldf,它使用 RSQLite。你也可以直接使用 RSQLite。请参阅 RSQLite 中的 ?dbWriteTable
。请注意,如果你直接使用 dbWriteTable
,可能会出现行结束符问题,而 sqldf
通常会自动处理。
如果你的意图是将文件读入数据库后立即将其读入 R,并且之后不再需要数据库,则请参见:
http://code.google.com/p/sqldf/#Example_13._read.csv.sql_and_read.csv2.sql
library(sqldf)
会加载sqldf包,使用sqldf
命令需要该包。 - G. Grothendieck