上のRubyスクリプトはそのための準備です。似たようなのはこの辺でやっているんだけど、csvじゃなくてDBから取ってきてっていうのの練習です。
まず使うための準備。ライブラリのインストールとか。SQLiteを叩くためのライブラリはいくつかあるようだけど、RSQLiteっていうのにしてみた。
install.packages("RSQLite") library("RSQLite") m <- dbDriver("SQLite") con <- dbConnect(m, dbname = "counter.db")
使い方も簡単で、こんな感じ。両方とも初歩の初歩くらいを知っている人だったら分かると思う。うーん、でも正規表現っぽいことやりたいなー。
> head(dbGetQuery(con,"select date from counter where Date like '2008-01-01%'")) date 1 2008-01-01 23:29:01 2 2008-01-01 23:28:29 3 2008-01-01 23:26:34 4 2008-01-01 23:26:24 5 2008-01-01 23:01:10 6 2008-01-01 22:56:19
で、例えば1月のアクセス数を描きたいときに、こういうベクトルが必要になってくる。
[1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
そうでないとこんなことになってしまう。1日のアクセスは01と言う形じゃないと行けない。
> head(dbGetQuery(con,"select date from counter where Date like '2008-01-1%'")) date 1 2008-01-10 23:27:00 2 2008-01-10 23:26:55 3 2008-01-10 23:18:45 4 2008-01-10 23:07:08 5 2008-01-10 22:58:17 6 2008-01-10 22:53:55
というわけでfotmatしてやるのが必要。この辺を参考にしつつ*1。
> sapply((1:10),function(x){sprintf("%02i",x)}) [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
で、こんな感じに変換してやる。
> (hoge <- unlist(sapply(sapply((1:30),function(x){sprintf("%02i",x)}),function(x){ + dbGetQuery(con, + paste("select count(date) from counter where Date like '2008-01-",x,"%'",sep="")) + }))) 01.count(date) 02.count(date) 03.count(date) 04.count(date) 05.count(date) 81 123 112 95 153 06.count(date) 07.count(date) 08.count(date) 09.count(date) 10.count(date) 202 258 214 272 167 11.count(date) 12.count(date) 13.count(date) 14.count(date) 15.count(date) 217 197 233 858 281 16.count(date) 17.count(date) 18.count(date) 19.count(date) 20.count(date) 285 276 526 397 479 21.count(date) 22.count(date) 23.count(date) 24.count(date) 25.count(date) 357 1132 511 519 221 26.count(date) 27.count(date) 28.count(date) 29.count(date) 30.count(date) 399 339 519 409 285
グラフとかを書いてみる。まあ、はてなカウンターで見れるわけだけど。
> names(hoge) <- c() > hoge [1] 81 123 112 95 153 202 258 214 272 167 217 197 233 858 281 [16] 285 276 526 397 479 357 1132 511 519 221 399 339 519 409 285 > plot(hoge,pch=21,type="b",xlab="day",ylab="number of access",main="change of access",lwd=5,cex=2,lty=1,col=2)
アクセス数が多そうに見えますが、開発合宿でインフレを起こしていた時です。
*1:sprint関数がベクトル対応してればいいのになー