Rからsqlite を使う rsqliteの導入

Rからsqlite を使う rsqliteの導入

まず、インストール

install.packages("RSQLite")

ためす。

drv<-dbDriver("SQLite")
con<-dbConnect(drv,dbname="test.sqlite")
dbGetQuery(con,"create table test (a,b)")
NULL
dbGetQuery(con,"insert into test values(1,2)")
NULL
a<-dbGetQuery(con,"select * from test")
> a
  a b
1 1 2
> dbGetQuery(con,"insert into test values(3,4)")
> a<-dbGetQuery(con,"select * from test")
> > a
  a b
1 1 2
2 3 4

一括してデータをデータフレームに

> d<-data.frame(1:10,1:10)
> names(d)<-c("a","b")
> dbGetQuery(con, "drop table if exists test2")
> dbWriteTable(con,"test2",d,row.names=F)
> dbGetQuery(con, "select * from test2")
    a  b
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10
> dbGetQuery(con, "select a from test2")
    a
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

テーブルデータの一括読み込み
id 2006-11-1 2006-11-2 …というデータ

data_table<-dbReadTable(con,"food_count_data")         
for(i in 1:length(data_table[,1])){
    lenlen<-length(data_table[i,])
                        q<-as.numeric(as.vector(data_table[i,][2:lenlen]))
}