2010-12-02 54 views

回答

19

您可以在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") 

上述用途sqldf它采用RSQLite。您也可以直接使用RSQLite。请参阅RSQLite中的?dbWriteTable。请注意,如果直接使用dbWriteTablesqldf将自动处理(通常),则可能会出现行结尾问题。

如果你的目的是将其读入数据库后立即文件读入到R和你并不真正需要后,该数据库,然后看到:

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

+0

sqldf是太棒了!看看这个答案以及http://stackoverflow.com/questions/4350131/unix-importing-large-csv-into-sqlite – Jay 2011-01-27 18:51:28