SlideShare a Scribd company logo
1 of 18
Download to read offline
R を SQL で操る
RDB をつかってる人でも R がとっつきやすくなる。




                              簑田 高志
目次



1 .自己紹介
2. Sqldf パッケージの紹介
3.ちょっと応用…



03/05/11            2
自己紹介
 ●


 ●   Twitter       aad34210
 ●                 http://pracmper.blogspot.com/
 ●


 ●


 ●                                    Web

 ●


               ●




03/05/11                                              3
質問

   まずは…ちょっとみなさんに質問。




03/05/11               4
質問

   まずは…ちょっとみなさんに質問。
    ・ R を使ったことがある人




03/05/11               5
質問

   まずは…ちょっとみなさんに質問。
    ・ R を使ったことがある人
    ・ RDB を SQL を使って操作したこ
   とがある人




03/05/11                    6
質問

   まずは…ちょっとみなさんに質問。
    ・ R を使ったことがある人
    ・ RDB を SQL を使って操作したこ
     とがある人
    ・ R で集計作業がめんどくさい!
      ( ・ д ・ ) チッ
     って思ったことことがある人

03/05/11                    7
sqldf パッケージ
   R で集計作業するときには…
     head(diamonds)
       carat        cut color clarity depth table price    x    y    z
     1 0.23      Ideal      E     SI2 61.5     55   326 3.95 3.98 2.43
     2 0.21    Premium      E     SI1 59.8     61   326 3.89 3.84 2.31
     3 0.23       Good      E     VS1 56.9     65   327 4.05 4.07 2.31
     4 0.29    Premium      I     VS2 62.4     58   334 4.20 4.23 2.63
     5 0.31       Good      J     SI2 63.3     58   335 4.34 4.35 2.75
     6 0.24 Very Good       J    VVS2 62.8     57   336 3.94 3.96 2.48


   #Price Cut
     price_sum <- aggregate(diamonds[,c(7)] , list(cut = diamonds$cut) , sum)
                  Cut
     other_mean <- aggregate(diamonds[,c(5:10)] , list(cut = diamonds$cut) , mean)
                                 Merge
     merge(price_sum , other_mean , by = c("cut"))



   ( ・ д ・ ) チッ>計算したい関数ごとでコード書かなきゃいけない…
                 DataFrame を簡単に集計したい。



03/05/11                                                                             8
Sqldf パッケージ
     ●
      R を使ってて
     ●
      集計がめんどくさい ( ・ д ・ ) チッ
     ●
      SQL を使ったことがある方。

     そんなあなたに今日は     sqldf   パッケージ
     を紹介します。




03/05/11                            9
sqldf パッケージ
 sqldf
 sqldf is an R package for runing SQL statements on R data frames, optimized for convenience. The user
 simply specifies an SQL statement in R using data frame names in place of table names and a database with
 appropriate table layouts/schema is automatically created, the data frames are automatically loaded into
 the database, the specified SQL statement is performed, the result is read back into R and the database is
 deleted all automatically behind the scenes making the database's existence transparent to the user who
 only specifies the SQL statement. Surprisingly this can at times be even faster than the corresponding pure
 R calculation (although the purpose of the project is convenience and not speed).
                                                                             http://code.google.com/p/sqldf/

 (
     sqldf             R                            SQL
           DB                                                                       SQL
            R                                  DB




03/05/11                                                                                                       10
sqldf パッケージ
   #sqldf
   install.packages("sqldf")
   library(sqldf)




    sqldf(”          SQL         ”

    #
    #iris
      sqldf("SELECT COUNT(*) as iris_count FROM iris")
      iris_count
    1        150


    #iris    Secies
    >sqldf("SELECT Species , COUNT(*) as iris_count FROM iris GROUP BY Species")
         Species iris_count
    1     setosa         50
    2 versicolor         50
    3 virginica          50




03/05/11                                                                           11
sqldf パッケージ
    #
    #           .
        iris2 <- iris
        colnames(iris2) <- c("Sepal_Length" , "Sepal_Width" , "Petal_Length" ,"Petal_Width" , "Species")
        head(iris2)


    #Specis
      sqldf("
      SELECT
          Species ,
          COUNT(Species) as Species_num,
          AVG(Sepal_Length) as average_Lentgh,
          AVG(Sepal_Width) as average_width
      FROM
          iris2
      GROUP BY
          Species
      ")
         Species Species_num average_Lentgh average_width
    1      setosa          50          5.006        3.428
    2 versicolor           50          5.936        2.770
    3 virginica            50          6.588        2.974




03/05/11                                                                                                   12
sqldf パッケージ
    #
    #Petal.Length
    #            WHERE

    >sqldf("SELECT   * FROM iris2 WHERE Petal_Length >= (select avg(Petal_Length) from iris2)")

        Sepal_Length Sepal_Width Petal_Length Petal_Width    Species
    1            7.0         3.2          4.7         1.4 versicolor
    2            6.4         3.2          4.5         1.5 versicolor
    3            6.9         3.1          4.9         1.5 versicolor
    4            5.5         2.3          4.0         1.3 versicolor
    5            6.5         2.8          4.6         1.5 versicolor
    6            5.7         2.8
                                   ・
                                   ・
                                          4.5         1.3 versicolor
                                   ・
                                   ・
                                   ・
    avg(Petal_Length) =3.758                                                     





03/05/11                                                                                          13
sqldf パッケージ
    #
    #
    #Species
    var <- "setosa"
    sql_head <- "SELECT * FROM iris2 WHERE Species = "
    sql_str <- paste(sql_head , "'", var ,"'" , collapse = "" , sep = "")
    sqldf(sql_str)

           Sepal_Length Sepal_Width Petal_Length Petal_Width Species
     1              5.1         3.5          1.4         0.2 setosa
     2              4.9         3.0          1.4         0.2 setosa
     3              4.7         3.2          1.3         0.2 setosa
     4              4.6         3.1          1.5         0.2 setosa
     5              5.0         3.6          1.4         0.2 setosa
                                   ・
                                   ・
                                   ・
                                   ・
                                   ・

    #            Function
    Sepal_search <- function(var){
    sql_head <- "SELECT * FROM iris2 WHERE Species = "
    sql_str <- paste(sql_head , "'", var ,"'" , collapse = "" , sep = "")
    print(sqldf(sql_str))
    }
    #
    Sepal_search(var = "versicolor")




03/05/11                                                                         14
sqldf パッケージ
    #
    #
    #R                  sqldf

    # R Code
    R_Code <- function(){
         price_sum <- aggregate(diamonds[,c(7)] , list(cut = diamonds$cut) , sum)
         other_mean <- aggregate(diamonds[,c(5,7:10)] , list(cut = diamonds$cut) , mean)
         merge(price_sum , other_mean , by = c("cut"))
    }
    system.time(R_Code())


    # sqldf
    sql_df_code <- function(){
    sqldf("
         SELECT
               cut, SUM(price), avg(depth), avg(price), avg(x), avg(y), avg(z)
         FROM diamonds
         GROUP BY cut
         ")
    }


    #
    system.time(R_Code())
    system.time(sql_df_code())




03/05/11                                                                                   15
sqldf パッケージ
    #
      #R aggregate ,merge
      system.time(R_Code())
         user system elapsed
        0.468   0.041   0.541

      #sqldf
      system.time(sql_df_code())
         user system elapsed
        0.841   0.036   0.895

      ・ R のコードと、 sqldf のコードとでは、 R のコードのほうが早かった!
      ・コードの書きやすさとスピードのトレードオフですかね…




03/05/11                                          16
まとめ
1.R                                  sqldf
            SQL

2.
     sqldf(“[SQL]”)
                 R

3.                Function   paste           SQL
                   sqldf

4.                 R                  …




03/05/11                                           17
m(__)m




03/05/11       18

More Related Content

What's hot

MySQLステータスモニタリング
MySQLステータスモニタリングMySQLステータスモニタリング
MySQLステータスモニタリングyoku0825
 
MySQLインストールのお作法
MySQLインストールのお作法MySQLインストールのお作法
MySQLインストールのお作法Meiji Kimura
 
MySQLerの7つ道具
MySQLerの7つ道具MySQLerの7つ道具
MySQLerの7つ道具yoku0825
 
雑なMySQLパフォーマンスチューニング
雑なMySQLパフォーマンスチューニング雑なMySQLパフォーマンスチューニング
雑なMySQLパフォーマンスチューニングyoku0825
 
My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1Makoto Haruyama
 
データベース05 - SQL(SELECT:結合,副問合せ)
データベース05 - SQL(SELECT:結合,副問合せ)データベース05 - SQL(SELECT:結合,副問合せ)
データベース05 - SQL(SELECT:結合,副問合せ)Kenta Oku
 
光のMySQL 5.7
光のMySQL 5.7光のMySQL 5.7
光のMySQL 5.7yoku0825
 
データベース06 - SQL(VIEW, ALTER, GRANTなど)
データベース06 - SQL(VIEW, ALTER, GRANTなど)データベース06 - SQL(VIEW, ALTER, GRANTなど)
データベース06 - SQL(VIEW, ALTER, GRANTなど)Kenta Oku
 
T sql の parse と generator
T sql の parse と generatorT sql の parse と generator
T sql の parse と generatorOda Shinsuke
 
Javaにおけるデータシリアライズと圧縮
Javaにおけるデータシリアライズと圧縮Javaにおけるデータシリアライズと圧縮
Javaにおけるデータシリアライズと圧縮moai kids
 
ペパボ de MySQL
ペパボ de MySQLペパボ de MySQL
ペパボ de MySQLyoku0825
 
MySQL日本語利用徹底入門
MySQL日本語利用徹底入門MySQL日本語利用徹底入門
MySQL日本語利用徹底入門Mikiya Okuno
 
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpring
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpringオープンソースRDBMS新機能ランダウンOSC2017TokyoSpring
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpringMeiji Kimura
 
配布用Beginnerならきっと役立つmaster slave環境
配布用Beginnerならきっと役立つmaster slave環境配布用Beginnerならきっと役立つmaster slave環境
配布用Beginnerならきっと役立つmaster slave環境yut148atgmaildotcom
 
MySQLerの7つ道具 plus
MySQLerの7つ道具 plusMySQLerの7つ道具 plus
MySQLerの7つ道具 plusyoku0825
 

What's hot (18)

Random Forests 不徹底入門
Random Forests 不徹底入門Random Forests 不徹底入門
Random Forests 不徹底入門
 
MySQLステータスモニタリング
MySQLステータスモニタリングMySQLステータスモニタリング
MySQLステータスモニタリング
 
MySQLインストールのお作法
MySQLインストールのお作法MySQLインストールのお作法
MySQLインストールのお作法
 
MySQLerの7つ道具
MySQLerの7つ道具MySQLerの7つ道具
MySQLerの7つ道具
 
雑なMySQLパフォーマンスチューニング
雑なMySQLパフォーマンスチューニング雑なMySQLパフォーマンスチューニング
雑なMySQLパフォーマンスチューニング
 
My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1My sql casual_in_fukuoka_vol1
My sql casual_in_fukuoka_vol1
 
データベース05 - SQL(SELECT:結合,副問合せ)
データベース05 - SQL(SELECT:結合,副問合せ)データベース05 - SQL(SELECT:結合,副問合せ)
データベース05 - SQL(SELECT:結合,副問合せ)
 
光のMySQL 5.7
光のMySQL 5.7光のMySQL 5.7
光のMySQL 5.7
 
データベース06 - SQL(VIEW, ALTER, GRANTなど)
データベース06 - SQL(VIEW, ALTER, GRANTなど)データベース06 - SQL(VIEW, ALTER, GRANTなど)
データベース06 - SQL(VIEW, ALTER, GRANTなど)
 
T sql の parse と generator
T sql の parse と generatorT sql の parse と generator
T sql の parse と generator
 
Javaにおけるデータシリアライズと圧縮
Javaにおけるデータシリアライズと圧縮Javaにおけるデータシリアライズと圧縮
Javaにおけるデータシリアライズと圧縮
 
ペパボ de MySQL
ペパボ de MySQLペパボ de MySQL
ペパボ de MySQL
 
MySQL日本語利用徹底入門
MySQL日本語利用徹底入門MySQL日本語利用徹底入門
MySQL日本語利用徹底入門
 
Gorinphp0729
Gorinphp0729Gorinphp0729
Gorinphp0729
 
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpring
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpringオープンソースRDBMS新機能ランダウンOSC2017TokyoSpring
オープンソースRDBMS新機能ランダウンOSC2017TokyoSpring
 
配布用Beginnerならきっと役立つmaster slave環境
配布用Beginnerならきっと役立つmaster slave環境配布用Beginnerならきっと役立つmaster slave環境
配布用Beginnerならきっと役立つmaster slave環境
 
MySQLerの7つ道具 plus
MySQLerの7つ道具 plusMySQLerの7つ道具 plus
MySQLerの7つ道具 plus
 
ヤフーのRDBと最新のMySQLの検証結果#yjdsw3
ヤフーのRDBと最新のMySQLの検証結果#yjdsw3ヤフーのRDBと最新のMySQLの検証結果#yjdsw3
ヤフーのRDBと最新のMySQLの検証結果#yjdsw3
 

Similar to Tokyo r sqldf

Rユーザのためのspark入門
Rユーザのためのspark入門Rユーザのためのspark入門
Rユーザのためのspark入門Shintaro Fukushima
 
textsearch_jaで全文検索
textsearch_jaで全文検索textsearch_jaで全文検索
textsearch_jaで全文検索Akio Ishida
 
Why dont you_create_new_spark_jl
Why dont you_create_new_spark_jlWhy dont you_create_new_spark_jl
Why dont you_create_new_spark_jlShintaro Fukushima
 
MySQLを割と一人で300台管理する技術
MySQLを割と一人で300台管理する技術MySQLを割と一人で300台管理する技術
MySQLを割と一人で300台管理する技術yoku0825
 
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)nabe-abk
 
データベースのお話
データベースのお話データベースのお話
データベースのお話Hidekazu Tanaka
 
めんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaめんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaKazuhiro Sera
 
[LT] T sql の parse と generator
[LT] T sql の parse と generator[LT] T sql の parse と generator
[LT] T sql の parse と generatorOda Shinsuke
 
Rのデータ構造とメモリ管理
Rのデータ構造とメモリ管理Rのデータ構造とメモリ管理
Rのデータ構造とメモリ管理Takeshi Arabiki
 
More Better Nested Set
More Better Nested SetMore Better Nested Set
More Better Nested Setxibbar
 
Learning spaerk chapter03
Learning spaerk chapter03Learning spaerk chapter03
Learning spaerk chapter03Akimitsu Takagi
 
Maatkit で MySQL チューニング
Maatkit で MySQL チューニングMaatkit で MySQL チューニング
Maatkit で MySQL チューニングKensuke Nagae
 
Ruby on Rails3 Tutorial Chapter3
Ruby on Rails3 Tutorial Chapter3Ruby on Rails3 Tutorial Chapter3
Ruby on Rails3 Tutorial Chapter3Sea Mountain
 
RのffとbigmemoryとRevoScaleRとを比較してみた
RのffとbigmemoryとRevoScaleRとを比較してみたRのffとbigmemoryとRevoScaleRとを比較してみた
RのffとbigmemoryとRevoScaleRとを比較してみたKazuya Wada
 
第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)Masanori Machii
 

Similar to Tokyo r sqldf (20)

Rユーザのためのspark入門
Rユーザのためのspark入門Rユーザのためのspark入門
Rユーザのためのspark入門
 
textsearch_jaで全文検索
textsearch_jaで全文検索textsearch_jaで全文検索
textsearch_jaで全文検索
 
Why dont you_create_new_spark_jl
Why dont you_create_new_spark_jlWhy dont you_create_new_spark_jl
Why dont you_create_new_spark_jl
 
scala-kaigi1-sbt
scala-kaigi1-sbtscala-kaigi1-sbt
scala-kaigi1-sbt
 
MySQLを割と一人で300台管理する技術
MySQLを割と一人で300台管理する技術MySQLを割と一人で300台管理する技術
MySQLを割と一人で300台管理する技術
 
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
毎秒2000Requestを捌くPerl製CMSの内部構造(Debianサーバ1台にて)
 
Maatkitの紹介
Maatkitの紹介Maatkitの紹介
Maatkitの紹介
 
hscj2019_ishizaki_public
hscj2019_ishizaki_publichscj2019_ishizaki_public
hscj2019_ishizaki_public
 
データベースのお話
データベースのお話データベースのお話
データベースのお話
 
めんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaめんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scala
 
[LT] T sql の parse と generator
[LT] T sql の parse と generator[LT] T sql の parse と generator
[LT] T sql の parse と generator
 
Gorinphp0729
Gorinphp0729Gorinphp0729
Gorinphp0729
 
20140920 tokyo r43
20140920 tokyo r4320140920 tokyo r43
20140920 tokyo r43
 
Rのデータ構造とメモリ管理
Rのデータ構造とメモリ管理Rのデータ構造とメモリ管理
Rのデータ構造とメモリ管理
 
More Better Nested Set
More Better Nested SetMore Better Nested Set
More Better Nested Set
 
Learning spaerk chapter03
Learning spaerk chapter03Learning spaerk chapter03
Learning spaerk chapter03
 
Maatkit で MySQL チューニング
Maatkit で MySQL チューニングMaatkit で MySQL チューニング
Maatkit で MySQL チューニング
 
Ruby on Rails3 Tutorial Chapter3
Ruby on Rails3 Tutorial Chapter3Ruby on Rails3 Tutorial Chapter3
Ruby on Rails3 Tutorial Chapter3
 
RのffとbigmemoryとRevoScaleRとを比較してみた
RのffとbigmemoryとRevoScaleRとを比較してみたRのffとbigmemoryとRevoScaleRとを比較してみた
RのffとbigmemoryとRevoScaleRとを比較してみた
 
第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)第2回品川Redmine勉強会(日本語全文検索)
第2回品川Redmine勉強会(日本語全文検索)
 

More from Takashi Minoda

Introduction r (R入門)
Introduction r (R入門)Introduction r (R入門)
Introduction r (R入門)Takashi Minoda
 
RStudioでRをはじめよう(R for Beginner using RStudio)
RStudioでRをはじめよう(R for Beginner using RStudio)RStudioでRをはじめよう(R for Beginner using RStudio)
RStudioでRをはじめよう(R for Beginner using RStudio)Takashi Minoda
 
RからGoogle Cloud Vision API を利用する
RからGoogle Cloud Vision API を利用するRからGoogle Cloud Vision API を利用する
RからGoogle Cloud Vision API を利用するTakashi Minoda
 
TokyoR:RMarkdownでレポート作成
TokyoR:RMarkdownでレポート作成TokyoR:RMarkdownでレポート作成
TokyoR:RMarkdownでレポート作成Takashi Minoda
 
Rとデータベース 第61回 Tokyo.R
Rとデータベース 第61回 Tokyo.RRとデータベース 第61回 Tokyo.R
Rとデータベース 第61回 Tokyo.RTakashi Minoda
 
Tokyo r24 r_graph_tutorial
Tokyo r24 r_graph_tutorialTokyo r24 r_graph_tutorial
Tokyo r24 r_graph_tutorialTakashi Minoda
 

More from Takashi Minoda (20)

Introduction r (R入門)
Introduction r (R入門)Introduction r (R入門)
Introduction r (R入門)
 
RStudioでRをはじめよう(R for Beginner using RStudio)
RStudioでRをはじめよう(R for Beginner using RStudio)RStudioでRをはじめよう(R for Beginner using RStudio)
RStudioでRをはじめよう(R for Beginner using RStudio)
 
RからGoogle Cloud Vision API を利用する
RからGoogle Cloud Vision API を利用するRからGoogle Cloud Vision API を利用する
RからGoogle Cloud Vision API を利用する
 
TokyoR:RMarkdownでレポート作成
TokyoR:RMarkdownでレポート作成TokyoR:RMarkdownでレポート作成
TokyoR:RMarkdownでレポート作成
 
Rとデータベース 第61回 Tokyo.R
Rとデータベース 第61回 Tokyo.RRとデータベース 第61回 Tokyo.R
Rとデータベース 第61回 Tokyo.R
 
Tokyo r50 beginner_2
Tokyo r50 beginner_2Tokyo r50 beginner_2
Tokyo r50 beginner_2
 
Tokyo r49 beginner
Tokyo r49 beginnerTokyo r49 beginner
Tokyo r49 beginner
 
Tokyo r47 beginner
Tokyo r47 beginnerTokyo r47 beginner
Tokyo r47 beginner
 
Tokyo r47 beginner_2
Tokyo r47 beginner_2Tokyo r47 beginner_2
Tokyo r47 beginner_2
 
Tokyo r45 beginner_2
Tokyo r45 beginner_2Tokyo r45 beginner_2
Tokyo r45 beginner_2
 
Tokyo r39 beginner
Tokyo r39 beginnerTokyo r39 beginner
Tokyo r39 beginner
 
Tokyo r38
Tokyo r38Tokyo r38
Tokyo r38
 
Tokyo r33 beginner
Tokyo r33 beginnerTokyo r33 beginner
Tokyo r33 beginner
 
Tokyo r30 anova_part2
Tokyo r30 anova_part2Tokyo r30 anova_part2
Tokyo r30 anova_part2
 
Tokyo r30 anova
Tokyo r30 anovaTokyo r30 anova
Tokyo r30 anova
 
Tokyo r30 beginner
Tokyo r30 beginnerTokyo r30 beginner
Tokyo r30 beginner
 
Tokyo r28 1
Tokyo r28 1Tokyo r28 1
Tokyo r28 1
 
Tokyo r27
Tokyo r27Tokyo r27
Tokyo r27
 
Tokyo r24 r_graph_tutorial
Tokyo r24 r_graph_tutorialTokyo r24 r_graph_tutorial
Tokyo r24 r_graph_tutorial
 
Tokyo r21 修正版
Tokyo r21 修正版Tokyo r21 修正版
Tokyo r21 修正版
 

Tokyo r sqldf

  • 1. R を SQL で操る RDB をつかってる人でも R がとっつきやすくなる。 簑田 高志
  • 2. 目次 1 .自己紹介 2. Sqldf パッケージの紹介 3.ちょっと応用… 03/05/11 2
  • 3. 自己紹介 ● ● Twitter aad34210 ● http://pracmper.blogspot.com/ ● ● ● Web ● ● 03/05/11 3
  • 4. 質問 まずは…ちょっとみなさんに質問。 03/05/11 4
  • 5. 質問 まずは…ちょっとみなさんに質問。 ・ R を使ったことがある人 03/05/11 5
  • 6. 質問 まずは…ちょっとみなさんに質問。 ・ R を使ったことがある人  ・ RDB を SQL を使って操作したこ とがある人 03/05/11 6
  • 7. 質問 まずは…ちょっとみなさんに質問。 ・ R を使ったことがある人  ・ RDB を SQL を使って操作したこ   とがある人  ・ R で集計作業がめんどくさい!    ( ・ д ・ ) チッ   って思ったことことがある人 03/05/11 7
  • 8. sqldf パッケージ R で集計作業するときには… head(diamonds) carat cut color clarity depth table price x y z 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 #Price Cut price_sum <- aggregate(diamonds[,c(7)] , list(cut = diamonds$cut) , sum) Cut other_mean <- aggregate(diamonds[,c(5:10)] , list(cut = diamonds$cut) , mean) Merge merge(price_sum , other_mean , by = c("cut")) ( ・ д ・ ) チッ>計算したい関数ごとでコード書かなきゃいけない…               DataFrame を簡単に集計したい。 03/05/11 8
  • 9. Sqldf パッケージ ● R を使ってて ● 集計がめんどくさい ( ・ д ・ ) チッ ● SQL を使ったことがある方。 そんなあなたに今日は sqldf パッケージ を紹介します。 03/05/11 9
  • 10. sqldf パッケージ sqldf sqldf is an R package for runing SQL statements on R data frames, optimized for convenience. The user simply specifies an SQL statement in R using data frame names in place of table names and a database with appropriate table layouts/schema is automatically created, the data frames are automatically loaded into the database, the specified SQL statement is performed, the result is read back into R and the database is deleted all automatically behind the scenes making the database's existence transparent to the user who only specifies the SQL statement. Surprisingly this can at times be even faster than the corresponding pure R calculation (although the purpose of the project is convenience and not speed). http://code.google.com/p/sqldf/ ( sqldf R SQL DB SQL R DB 03/05/11 10
  • 11. sqldf パッケージ #sqldf install.packages("sqldf") library(sqldf) sqldf(” SQL ” # #iris sqldf("SELECT COUNT(*) as iris_count FROM iris") iris_count 1 150 #iris Secies >sqldf("SELECT Species , COUNT(*) as iris_count FROM iris GROUP BY Species") Species iris_count 1 setosa 50 2 versicolor 50 3 virginica 50 03/05/11 11
  • 12. sqldf パッケージ # # . iris2 <- iris colnames(iris2) <- c("Sepal_Length" , "Sepal_Width" , "Petal_Length" ,"Petal_Width" , "Species") head(iris2) #Specis sqldf(" SELECT Species , COUNT(Species) as Species_num, AVG(Sepal_Length) as average_Lentgh, AVG(Sepal_Width) as average_width FROM iris2 GROUP BY Species ") Species Species_num average_Lentgh average_width 1 setosa 50 5.006 3.428 2 versicolor 50 5.936 2.770 3 virginica 50 6.588 2.974 03/05/11 12
  • 13. sqldf パッケージ # #Petal.Length # WHERE >sqldf("SELECT * FROM iris2 WHERE Petal_Length >= (select avg(Petal_Length) from iris2)") Sepal_Length Sepal_Width Petal_Length Petal_Width Species 1 7.0 3.2 4.7 1.4 versicolor 2 6.4 3.2 4.5 1.5 versicolor 3 6.9 3.1 4.9 1.5 versicolor 4 5.5 2.3 4.0 1.3 versicolor 5 6.5 2.8 4.6 1.5 versicolor 6 5.7 2.8 ・ ・ 4.5 1.3 versicolor ・ ・ ・ avg(Petal_Length) =3.758 
 03/05/11 13
  • 14. sqldf パッケージ # # #Species var <- "setosa" sql_head <- "SELECT * FROM iris2 WHERE Species = " sql_str <- paste(sql_head , "'", var ,"'" , collapse = "" , sep = "") sqldf(sql_str) Sepal_Length Sepal_Width Petal_Length Petal_Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa ・ ・ ・ ・ ・ # Function Sepal_search <- function(var){ sql_head <- "SELECT * FROM iris2 WHERE Species = " sql_str <- paste(sql_head , "'", var ,"'" , collapse = "" , sep = "") print(sqldf(sql_str)) } # Sepal_search(var = "versicolor") 03/05/11 14
  • 15. sqldf パッケージ # # #R sqldf # R Code R_Code <- function(){ price_sum <- aggregate(diamonds[,c(7)] , list(cut = diamonds$cut) , sum) other_mean <- aggregate(diamonds[,c(5,7:10)] , list(cut = diamonds$cut) , mean) merge(price_sum , other_mean , by = c("cut")) } system.time(R_Code()) # sqldf sql_df_code <- function(){ sqldf(" SELECT cut, SUM(price), avg(depth), avg(price), avg(x), avg(y), avg(z) FROM diamonds GROUP BY cut ") } # system.time(R_Code()) system.time(sql_df_code()) 03/05/11 15
  • 16. sqldf パッケージ # #R aggregate ,merge system.time(R_Code()) user system elapsed 0.468 0.041 0.541 #sqldf system.time(sql_df_code()) user system elapsed 0.841 0.036 0.895 ・ R のコードと、 sqldf のコードとでは、 R のコードのほうが早かった! ・コードの書きやすさとスピードのトレードオフですかね… 03/05/11 16
  • 17. まとめ 1.R sqldf SQL 2. sqldf(“[SQL]”) R 3. Function paste SQL sqldf 4. R … 03/05/11 17