如何使用RSqlite将CSV导入sqlite?

lok*_*art 9 sqlite import r

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

G. *_*eck 20

你可以read.csv.sqlsqldf包中使用.只读一行代码.假设您要创建一个新数据库,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")
Run Code Online (Sandbox Code Playgroud)

以上使用sqldf,它使用RSQLite.您也可以直接使用RSQLite.请参阅?dbWriteTableRSQLite.需要注意的是可以有行尾问题,如果你直接这样做dbWriteTablesqldf会自动处理(一般).

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

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