如何使用RSqlite将CSV导入sqlite? [英] How to import CSV into sqlite using RSqlite?

查看:113
本文介绍了如何使用RSqlite将CSV导入sqlite?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为问题,我发现我可以在sqlite shell中使用 .import ,但似乎它在R环境中不起作用,有什么建议吗?

As question, I found that I can use .import in sqlite shell, but seems it is not working in R environment, any suggestions?

推荐答案

您可以在 sqldf <中使用 read.csv.sql / code>包。只读一行代码。假设您要创建一个新数据库,测试db,然后将文件读入其中,请尝试以下操作:

You can use read.csv.sql in the sqldf package. It is only one line of code to do the read. Assuming you want to create a new database, testingdb, and then read a file into it try this:

# 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 将自动处理(通常) 。

The above uses sqldf which uses RSQLite. You can also use RSQLite directly. See ?dbWriteTable in RSQLite. Note that there can be problems with line endings if you do it directly with dbWriteTable that sqldf will automatically handle (usually).

如果您打算在将文件读入数据库后立即将文件读入R并且之后您不需要数据库,那么请参阅:

If your intention was to read the file into R immediately after reading it into the database and you don't really need the database after that then see:

http://code.google.com/p/sqldf/#Example_13._read.csv.sql_and_read.csv2.sql

这篇关于如何使用RSqlite将CSV导入sqlite?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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