SlideShare uma empresa Scribd logo
1 de 70
Extend R with Rcpp!!!
     2010/09/19 Tsukuba.R#8
           id:mickey24
id: mickey24 (@mickey24)
Tsukuba.R
Tsukuba.R#4
   •R           Brainf*ck
     •   Brainf*ck

> hello <- "+++++++++[>++++++++>++++++++++
+>+++++<<<-]>.>++.+++++++..++
+.>-.------------.<++++++++.--------.++
+.------.--------.>+."
> brainfxxk(hello)
[1] "Hello, world!"

                        http://www.slideshare.net/mickey24/rbrainfck-1085191
Tsukuba.R#5
• Animation with R
 • library(animation)




                        http://d.hatena.ne.jp/mickey24/20090614
Tsukuba.R#6
• Extend R with C!!!
 •   C   R             (C             OpenCV                 )




                 http://d.hatena.ne.jp/mickey24/20091123/r_de_extension
Tsukuba.R#7
• Parallel Conputing in R
  •   snow




                    http://d.hatena.ne.jp/mickey24/20100510/tsukuba_r7
Tsukuba.R#8


Rcpp R
Outline
•        R    (C++)

• Rcpp
•
R   (C++)
C++ R
• C++         R
        (C/FORTRAN OK)

• C++              R
1.
     •
     •          C   R                     (40   50   )   www
         - Seeking for my unique color.
         http://d.hatena.ne.jp/syou6162/20090117/1232120983

2. R           C
C++ R
• C++   R                 API




extern "C" SEXP foo(SEXP x) {
  ...
}
C++ R
    1. C++ R
    2.                  .so
    3. R       .so
    4. .Call   .so


R                              C++
                     1. add_vector
                     2. cat_string
add_vector.cc
#include <R.h>
#include <Rdefines.h>

extern "C" SEXP add_vector(SEXP x, SEXP y) {
  PROTECT(x = AS_NUMERIC(x));
  PROTECT(y = AS_NUMERIC(y));

    const int n = LENGTH(x);
    SEXP z;
    PROTECT(z = allocVector(REALSXP, n));

    for (int i = 0; i < n; ++i) {
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];
    }

    UNPROTECT(3);
    return z;
}
add_vector.cc
•
$ R CMD SHLIB add_vector.cc


• .so
$ ls
add_vector.cc
add_vector.o
add_vector.so
add_vector.cc
•R    .so
> dyn.load("add_vector.so")



•
> .Call("add_vector", 1:3, 4:6)
[1] 5 7 9


                                  OK!
cat_string.cc
#include <R.h>
#include <Rdefines.h>
#include <string>

extern "C" SEXP cat_string(SEXP x, SEXP y) {
  PROTECT(x = AS_CHARACTER(x));
  PROTECT(y = AS_CHARACTER(y));

    SEXP z;
    PROTECT(z = allocVector(STRSXP, 1));

    std::string str(CHAR(STRING_ELT(x, 0)));
    str += CHAR(STRING_ELT(y, 0));

    SET_STRING_ELT(z, 0, mkChar(str.c_str()));

    UNPROTECT(3);
    return z;
}
cat_string.cc
•
$ R CMD SHLIB cat_string.cc


•R
> dyn.load("cat_string.so")
> .Call("cat_string", "foo", "bar")
[1] "foobar"

                                      OK!
R
•   PROTECT / UNPROTECT
    •
    •   UNPROTECT(n) →        n
                     …

    •                    GC

•   SEXP C++

•
    •   REAL(x)
    •   C++
Outline
•        R    (C++)

• Rcpp
•
Rcpp
Rcpp
•R          C++


 •
• C++   R
•
> install.packages("Rcpp")



•   Rcpp
Overview
•
> vignette("Rcpp-introduction")




•
OK
• Rcpp                    R




         add_vector.cc Rcpp
add_vector.cc (                          )
#include <R.h>
#include <Rdefines.h>

extern "C" SEXP add_vector(SEXP x, SEXP y) {
  PROTECT(x = AS_NUMERIC(x));
  PROTECT(y = AS_NUMERIC(y));

    const int n = LENGTH(x);
    SEXP z;
    PROTECT(z = allocVector(REALSXP, n));

    for (int i = 0; i < n; ++i) {
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];
    }

    UNPROTECT(3);
    return z;
}
add_vector_rcpp.cc
#include <Rcpp.h>

RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) {
  Rcpp::NumericVector x(xx);
  Rcpp::NumericVector y(yy);

    int n = x.length();
    Rcpp::NumericVector z(n);

    for (int i = 0; i < n; ++i) {
      z[i] = x[i] + y[i];
    }

    return z;
}
1. PROTECT / UNPROTECT
     •                    Rcpp


     •   UNPROTECT
2.
     REAL(x)
     •               []

     •      C++
                                 COOL!!!
#include <R.h>                                 #include <Rcpp.h>
#include <Rdefines.h>
                                               RcppExport SEXP add_vector_rcpp(SEXP xx,
extern "C" SEXP add_vector(SEXP x, SEXP y) {                                   SEXP yy) {
  PROTECT(x = AS_NUMERIC(x));                    Rcpp::NumericVector x(xx);
  PROTECT(y = AS_NUMERIC(y));                    Rcpp::NumericVector y(yy);

    const int n = LENGTH(x);                       const int n = x.length();
    SEXP z;                                        Rcpp::NumericVector z(n);
    PROTECT(z = allocVector(REALSXP, n));
                                                   for (int i = 0; i < n; ++i) {
    for (int i = 0; i < n; ++i) {                    z[i] = x[i] + y[i];
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];        }
    }
                                                   return z;
    UNPROTECT(3);                              }
    return z;
}
                                                         1. PROTECT / UNPROTECT
                                                         2. REAL(x)
Rcpp

   •            Makevars
       •   Rcpp.h

PKG_CXXFLAGS=$(shell Rscript -e "Rcpp:::CxxFlags()")
PKG_LIBS=$(shell Rscript -e "Rcpp:::LdFlags()")
Rcpp

•
$ R CMD SHLIB add_vector_rcpp.cc



> dyn.load("add_vector_rcpp.so")
> .Call("add_vector_rcpp", 1:3, 4:6)
[1] 5 7 9
NumericVector
• Rcpp::NumericVector
#include <Rcpp.h>

RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) {
  Rcpp::NumericVector x(xx);
  Rcpp::NumericVector y(yy);
  Rcpp::NumericVector z(x + y);

    return z;
}
C++
• SEXP        C++


#include <Rcpp.h>
#include <string>

RcppExport SEXP cat_string_rcpp(SEXP xx, SEXP yy) {
  std::string x(Rcpp::as<std::string>(xx));
  std::string y(Rcpp::as<std::string>(yy));
  std::string z(x + y);

    return Rcpp::wrap(z);
}
as wrap
• SEXP                      C++
 1. primitive       int, double, etc.
 2.             std::string, const char*
 3.               std::vector<T>, std::list<T>
 4.               std::map<string, T>
 5. SEXP
 6. wrap
Rcpp

    PROTECT
   UNPROTECT

                REAL(x), CHAR(x),
                                    [] (                )
               STRING_ELT(x, i)
SEXP C++
                                           (as, wrap)

                                       Makervars
                                    Rcpp
Outline
•        R    (C++)

• Rcpp
•
• Rcpp

•    Rcpp
•             0.7                           n


    1. r2norm_for : R   for             (syou6162 )
    2. r2norm_cpp :           C++            (syou6162 )
    3. r2norm_rcpp : Rcpp


    > x <- r2norm_cpp(1000)
    > cor(x[,1], x[,2])
    [1] 0.7144986
    > plot(x)
                               http://d.hatena.ne.jp/syou6162/20090117/1232120983
r2norm_cpp.cc                                     r2norm_rcpp.cc
#include <R.h>                                   #include <Rcpp.h>
#include <Rdefines.h>
                                                 RcppExport SEXP r2norm_rcpp(SEXP num) {
extern "C" SEXP r2norm_cpp(SEXP num) {             const int n = Rcpp::as<int>(num);
  PROTECT(num = AS_INTEGER(num));                  Rcpp::NumericMatrix ans(n, 2);
  const int n = INTEGER(num)[0];
                                                     GetRNGstate();
    SEXP ans;
    PROTECT(ans = allocMatrix(REALSXP, n, 2));       double prevX1 = 2.0;
                                                     double prevX2 = 1.0;
    GetRNGstate();                                   for (int i = 0; i < n; ++i) {
                                                       prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) +
    double prevX1 = 2.0;                                 (norm_rand() * (1.0 - 0.7 * 0.7));
    double prevX2 = 1.0;                               ans(i, 0) = prevX1;
    for (int i = 0; i < n; ++i) {                      prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) +
      prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) +              (norm_rand() * (1.0 - 0.7 * 0.7));
        (norm_rand() * (1.0 - 0.7 * 0.7));             ans(i, 1) = prevX2;
      REAL(ans)[i] = prevX1;                         }
      prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) +          PutRNGstate();
        (norm_rand() * (1.0 - 0.7 * 0.7));
      REAL(ans)[i+n] = prevX2;                       return ans;
    }                                            }
    PutRNGstate();

    UNPROTECT(2);
    return ans;
}
n = 1,000 n = 10^4 n = 10^5 n = 10^6

R    for      0.035     0.330    3.372    33.982

       C++    0.001     0.003    0.028    0.312

    Rcpp      0.001     0.005    0.050    0.507

                                               sec
R    for            C++       Rcpp
sec
40.00


30.00


20.00


10.00


      0
           n=1000   n=10^4         n=10^5         n=10^6


      R   for                      67
(        vs Rcpp)
                                         C++       Rcpp
sec
 0.60


 0.45


 0.30


 0.15


      0
          n=1000   n=10^4       n=10^5         n=10^6
•   Rcpp       C++      R


•   R
           (PROTECT / UNPROTECT   )

•   SEXP C++

•
•   C++    R


•         R API         C++


•
                  C++         R
•   Rcpp: Seamless R and C++ Integration
    http://dirk.eddelbuettel.com/code/rcpp.html

•   Rcpp                  - Seeking for my unique color.
    http://d.hatena.ne.jp/syou6162/20100316/1268734140

•   C   R                          (40   50   )       www
    - Seeking for my unique color.
    http://d.hatena.ne.jp/syou6162/20090117/1232120983

•   Writing R Extensions
    http://cran.r-project.org/doc/contrib/manuals-jp/R-exts.jp.pdf
Tsukuba.R#7
RTetris
2010/09/19 Tsukuba.R#8
      id:mickey24
RTetris
•   R(                   C++)
    •   Tsukuba.R#7 (           )

    •   tetris                      C++
        •            R

    •                ncurses


•                R
         R
RTetris                   R
•                 C++(Rcpp)
    •   ncurses       C++

•                      R
    •
• Tsukuba.R#8
…
•
1.
2.
3.
4.
•
•   ncurses

•   C++                 ncurses
           (             )

      RcppExport SEXP ncurses_initialize() {
        initscr();
        noecho();
        nodelay(stdscr, true);
        curs_set(0);

          return R_NilValue;
      }
R
•
•         R               (ry



•   C++       & ncurses
•   ncurses getch
    •                     ASCII                 -1

        RcppExport SEXP ncurses_getch() {
          return wrap(getch());
        }



•   R

    •
    •   proc.time()
        while (running) {
          key = ncurses_getch()
          if (key != -1) {      }


            now = proc.time()
            if (now[3] >= next_time) {      }


            Sys.sleep(0.001)
        }
•

•
    •           all

    •
        all(field[i,] == BLOCK)
•
                                       
   a11   a12   a13   a14                 1
  a21   a22   a23   a24           1    
A=
  a31
                            R=          
         a32   a33   a34       1        
   a41   a42   a43   a44        1
(                       )

•
                                              
       a11   a12   a13   a14                 1
     a21    a22   a23   a24           1       
AR = 
     a31
                             ×                 
             a32   a33   a34       1           
       a41   a42   a43   a44    1
                            
      a14    a13   a12   a11
     a24    a23   a22   a21 
   =a34
                             
             a33   a32   a31 
      a44    a43   a42   a41
(            )

•
                                 T
            a14    a13   a12   a11
           a24    a23   a22   a21 
    (AR) = 
        T
           a34
                                   
                   a33   a32   a31 
            a44    a43   a42   a41
                                  
             a14   a24   a34   a44
           a13    a23   a33   a43 
          =
           a12
                                   
                   a22   a32   a42 
             a11   a21   a31   a41
(                )

   •
                                                      
   a11   a12   a13   a14            a41   a31   a21   a11
  a21   a22   a23   a24          a42   a32   a22   a12 
A=
  a31
                          (RA)T =                       
         a32   a33   a34          a43   a33   a23   a13 
   a41   a42   a43   a44            a44   a34   a24   a14
•
•   R


    •
    •
•
Extend R with Rcpp!!!

Mais conteúdo relacionado

Mais procurados

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184Mahmoud Samir Fayed
 
RuleML2015: GRAAL - a toolkit for query answering with existential rules
RuleML2015:  GRAAL - a toolkit for query answering with existential rulesRuleML2015:  GRAAL - a toolkit for query answering with existential rules
RuleML2015: GRAAL - a toolkit for query answering with existential rulesRuleML
 
Java8 stream
Java8 streamJava8 stream
Java8 streamkoji lin
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow규영 허
 
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...GECon_Org Team
 
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them allGECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them allYauheni Akhotnikau
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojureRoy Rutto
 
The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181Mahmoud Samir Fayed
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & howlucenerevolution
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory ManagementAlan Uthoff
 

Mais procurados (20)

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
RuleML2015: GRAAL - a toolkit for query answering with existential rules
RuleML2015:  GRAAL - a toolkit for query answering with existential rulesRuleML2015:  GRAAL - a toolkit for query answering with existential rules
RuleML2015: GRAAL - a toolkit for query answering with existential rules
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Struct examples
Struct examplesStruct examples
Struct examples
 
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...
 
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them allGECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojure
 
Vectorization in ATLAS
Vectorization in ATLASVectorization in ATLAS
Vectorization in ATLAS
 
The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Lec06
Lec06Lec06
Lec06
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory Management
 

Destaque

R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦! R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦! Yurie Oka
 
今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門toilet_lunch
 
ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33horihorio
 
Extend R with C!!!
Extend R with C!!!Extend R with C!!!
Extend R with C!!!mickey24
 
セイバーメトリクス
セイバーメトリクスセイバーメトリクス
セイバーメトリクスMitsuo Shimohata
 
Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33Nobuaki Oshiro
 
ニコニコ動画タグネットワーク
ニコニコ動画タグネットワークニコニコ動画タグネットワーク
ニコニコ動画タグネットワークTeruki Shinohara
 
偽相関と偏相関係数
偽相関と偏相関係数偽相関と偏相関係数
偽相関と偏相関係数Teruki Shinohara
 
Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境Michitaka Iida
 
Collaborativefilteringwith r
Collaborativefilteringwith rCollaborativefilteringwith r
Collaborativefilteringwith rTeito Nakagawa
 
第31回TokyoR LT資料
第31回TokyoR LT資料第31回TokyoR LT資料
第31回TokyoR LT資料tetsuro ito
 
中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側Takekatsu Hiramura
 
第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション宏喜 佐野
 
Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」Nagi Teramo
 

Destaque (20)

R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦! R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦!
 
今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門
 
ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33
 
Extend R with C!!!
Extend R with C!!!Extend R with C!!!
Extend R with C!!!
 
ESS
ESSESS
ESS
 
セイバーメトリクス
セイバーメトリクスセイバーメトリクス
セイバーメトリクス
 
RでAHP
RでAHPRでAHP
RでAHP
 
Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33
 
ニコニコ動画タグネットワーク
ニコニコ動画タグネットワークニコニコ動画タグネットワーク
ニコニコ動画タグネットワーク
 
偽相関と偏相関係数
偽相関と偏相関係数偽相関と偏相関係数
偽相関と偏相関係数
 
Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境
 
Collaborativefilteringwith r
Collaborativefilteringwith rCollaborativefilteringwith r
Collaborativefilteringwith r
 
rzmq
rzmqrzmq
rzmq
 
第31回TokyoR LT資料
第31回TokyoR LT資料第31回TokyoR LT資料
第31回TokyoR LT資料
 
中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側
 
R3.0.0 is relased
R3.0.0 is relasedR3.0.0 is relased
R3.0.0 is relased
 
Tokyo r30 anova_part2
Tokyo r30 anova_part2Tokyo r30 anova_part2
Tokyo r30 anova_part2
 
第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション
 
Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」
 
Abテストと検定
Abテストと検定Abテストと検定
Abテストと検定
 

Semelhante a Extend R with Rcpp!!!

Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for RSeth Falcon
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdfImplement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdfmeerobertsonheyde608
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Jan Wedekind
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-stdPaul Phillips
 
Frsa
FrsaFrsa
Frsa_111
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and PolynomialAroosa Rajput
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdfTranslate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdffcsondhiindia
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for SpeedYung-Yu Chen
 
include.docx
include.docxinclude.docx
include.docxNhiPtaa
 

Semelhante a Extend R with Rcpp!!! (20)

Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
R and C++
R and C++R and C++
R and C++
 
R and cpp
R and cppR and cpp
R and cpp
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for R
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdfImplement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Frsa
FrsaFrsa
Frsa
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and Polynomial
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdfTranslate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
include.docx
include.docxinclude.docx
include.docx
 

Último

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Último (20)

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Extend R with Rcpp!!!

  • 1. Extend R with Rcpp!!! 2010/09/19 Tsukuba.R#8 id:mickey24
  • 4. Tsukuba.R#4 •R Brainf*ck • Brainf*ck > hello <- "+++++++++[>++++++++>++++++++++ +>+++++<<<-]>.>++.+++++++..++ +.>-.------------.<++++++++.--------.++ +.------.--------.>+." > brainfxxk(hello) [1] "Hello, world!" http://www.slideshare.net/mickey24/rbrainfck-1085191
  • 5. Tsukuba.R#5 • Animation with R • library(animation) http://d.hatena.ne.jp/mickey24/20090614
  • 6. Tsukuba.R#6 • Extend R with C!!! • C R (C OpenCV ) http://d.hatena.ne.jp/mickey24/20091123/r_de_extension
  • 7. Tsukuba.R#7 • Parallel Conputing in R • snow http://d.hatena.ne.jp/mickey24/20100510/tsukuba_r7
  • 9. Outline • R (C++) • Rcpp •
  • 10. R (C++)
  • 11. C++ R • C++ R (C/FORTRAN OK) • C++ R
  • 12. 1. • • C R (40 50 ) www - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20090117/1232120983 2. R C
  • 13. C++ R • C++ R API extern "C" SEXP foo(SEXP x) { ... }
  • 14. C++ R 1. C++ R 2. .so 3. R .so 4. .Call .so R C++ 1. add_vector 2. cat_string
  • 15. add_vector.cc #include <R.h> #include <Rdefines.h> extern "C" SEXP add_vector(SEXP x, SEXP y) { PROTECT(x = AS_NUMERIC(x)); PROTECT(y = AS_NUMERIC(y)); const int n = LENGTH(x); SEXP z; PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } UNPROTECT(3); return z; }
  • 16. add_vector.cc • $ R CMD SHLIB add_vector.cc • .so $ ls add_vector.cc add_vector.o add_vector.so
  • 17. add_vector.cc •R .so > dyn.load("add_vector.so") • > .Call("add_vector", 1:3, 4:6) [1] 5 7 9 OK!
  • 18. cat_string.cc #include <R.h> #include <Rdefines.h> #include <string> extern "C" SEXP cat_string(SEXP x, SEXP y) { PROTECT(x = AS_CHARACTER(x)); PROTECT(y = AS_CHARACTER(y)); SEXP z; PROTECT(z = allocVector(STRSXP, 1)); std::string str(CHAR(STRING_ELT(x, 0))); str += CHAR(STRING_ELT(y, 0)); SET_STRING_ELT(z, 0, mkChar(str.c_str())); UNPROTECT(3); return z; }
  • 19. cat_string.cc • $ R CMD SHLIB cat_string.cc •R > dyn.load("cat_string.so") > .Call("cat_string", "foo", "bar") [1] "foobar" OK!
  • 20. R • PROTECT / UNPROTECT • • UNPROTECT(n) → n … • GC • SEXP C++ • • REAL(x) • C++
  • 21. Outline • R (C++) • Rcpp •
  • 22. Rcpp
  • 23. Rcpp •R C++ • • C++ R
  • 26. OK • Rcpp R add_vector.cc Rcpp
  • 27. add_vector.cc ( ) #include <R.h> #include <Rdefines.h> extern "C" SEXP add_vector(SEXP x, SEXP y) { PROTECT(x = AS_NUMERIC(x)); PROTECT(y = AS_NUMERIC(y)); const int n = LENGTH(x); SEXP z; PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } UNPROTECT(3); return z; }
  • 28. add_vector_rcpp.cc #include <Rcpp.h> RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) { Rcpp::NumericVector x(xx); Rcpp::NumericVector y(yy); int n = x.length(); Rcpp::NumericVector z(n); for (int i = 0; i < n; ++i) { z[i] = x[i] + y[i]; } return z; }
  • 29. 1. PROTECT / UNPROTECT • Rcpp • UNPROTECT 2. REAL(x) • [] • C++ COOL!!!
  • 30. #include <R.h> #include <Rcpp.h> #include <Rdefines.h> RcppExport SEXP add_vector_rcpp(SEXP xx, extern "C" SEXP add_vector(SEXP x, SEXP y) { SEXP yy) { PROTECT(x = AS_NUMERIC(x)); Rcpp::NumericVector x(xx); PROTECT(y = AS_NUMERIC(y)); Rcpp::NumericVector y(yy); const int n = LENGTH(x); const int n = x.length(); SEXP z; Rcpp::NumericVector z(n); PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) { z[i] = x[i] + y[i]; REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } } return z; UNPROTECT(3); } return z; } 1. PROTECT / UNPROTECT 2. REAL(x)
  • 31. Rcpp • Makevars • Rcpp.h PKG_CXXFLAGS=$(shell Rscript -e "Rcpp:::CxxFlags()") PKG_LIBS=$(shell Rscript -e "Rcpp:::LdFlags()")
  • 32. Rcpp • $ R CMD SHLIB add_vector_rcpp.cc > dyn.load("add_vector_rcpp.so") > .Call("add_vector_rcpp", 1:3, 4:6) [1] 5 7 9
  • 33. NumericVector • Rcpp::NumericVector #include <Rcpp.h> RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) { Rcpp::NumericVector x(xx); Rcpp::NumericVector y(yy); Rcpp::NumericVector z(x + y); return z; }
  • 34. C++ • SEXP C++ #include <Rcpp.h> #include <string> RcppExport SEXP cat_string_rcpp(SEXP xx, SEXP yy) { std::string x(Rcpp::as<std::string>(xx)); std::string y(Rcpp::as<std::string>(yy)); std::string z(x + y); return Rcpp::wrap(z); }
  • 35. as wrap • SEXP C++ 1. primitive int, double, etc. 2. std::string, const char* 3. std::vector<T>, std::list<T> 4. std::map<string, T> 5. SEXP 6. wrap
  • 36. Rcpp PROTECT UNPROTECT REAL(x), CHAR(x), [] ( ) STRING_ELT(x, i) SEXP C++ (as, wrap) Makervars Rcpp
  • 37. Outline • R (C++) • Rcpp •
  • 38.
  • 39. • Rcpp • Rcpp
  • 40.
  • 41. 0.7 n 1. r2norm_for : R for (syou6162 ) 2. r2norm_cpp : C++ (syou6162 ) 3. r2norm_rcpp : Rcpp > x <- r2norm_cpp(1000) > cor(x[,1], x[,2]) [1] 0.7144986 > plot(x) http://d.hatena.ne.jp/syou6162/20090117/1232120983
  • 42. r2norm_cpp.cc r2norm_rcpp.cc #include <R.h> #include <Rcpp.h> #include <Rdefines.h> RcppExport SEXP r2norm_rcpp(SEXP num) { extern "C" SEXP r2norm_cpp(SEXP num) { const int n = Rcpp::as<int>(num); PROTECT(num = AS_INTEGER(num)); Rcpp::NumericMatrix ans(n, 2); const int n = INTEGER(num)[0]; GetRNGstate(); SEXP ans; PROTECT(ans = allocMatrix(REALSXP, n, 2)); double prevX1 = 2.0; double prevX2 = 1.0; GetRNGstate(); for (int i = 0; i < n; ++i) { prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) + double prevX1 = 2.0; (norm_rand() * (1.0 - 0.7 * 0.7)); double prevX2 = 1.0; ans(i, 0) = prevX1; for (int i = 0; i < n; ++i) { prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) + prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) + (norm_rand() * (1.0 - 0.7 * 0.7)); (norm_rand() * (1.0 - 0.7 * 0.7)); ans(i, 1) = prevX2; REAL(ans)[i] = prevX1; } prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) + PutRNGstate(); (norm_rand() * (1.0 - 0.7 * 0.7)); REAL(ans)[i+n] = prevX2; return ans; } } PutRNGstate(); UNPROTECT(2); return ans; }
  • 43.
  • 44. n = 1,000 n = 10^4 n = 10^5 n = 10^6 R for 0.035 0.330 3.372 33.982 C++ 0.001 0.003 0.028 0.312 Rcpp 0.001 0.005 0.050 0.507 sec
  • 45. R for C++ Rcpp sec 40.00 30.00 20.00 10.00 0 n=1000 n=10^4 n=10^5 n=10^6 R for 67
  • 46. ( vs Rcpp) C++ Rcpp sec 0.60 0.45 0.30 0.15 0 n=1000 n=10^4 n=10^5 n=10^6
  • 47.
  • 48. Rcpp C++ R • R (PROTECT / UNPROTECT ) • SEXP C++ •
  • 49. C++ R • R API C++ • C++ R
  • 50. Rcpp: Seamless R and C++ Integration http://dirk.eddelbuettel.com/code/rcpp.html • Rcpp - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20100316/1268734140 • C R (40 50 ) www - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20090117/1232120983 • Writing R Extensions http://cran.r-project.org/doc/contrib/manuals-jp/R-exts.jp.pdf
  • 51.
  • 54. RTetris • R( C++) • Tsukuba.R#7 ( ) • tetris C++ • R • ncurses • R R
  • 55. RTetris R • C++(Rcpp) • ncurses C++ • R • • Tsukuba.R#8
  • 56.
  • 57.
  • 58.
  • 59.
  • 61. • • ncurses • C++ ncurses ( ) RcppExport SEXP ncurses_initialize() { initscr(); noecho(); nodelay(stdscr, true); curs_set(0); return R_NilValue; }
  • 62. R • • R (ry • C++ & ncurses
  • 63. ncurses getch • ASCII -1 RcppExport SEXP ncurses_getch() { return wrap(getch()); } • R • • proc.time() while (running) { key = ncurses_getch() if (key != -1) { } now = proc.time() if (now[3] >= next_time) { } Sys.sleep(0.001) }
  • 64. • • • all • all(field[i,] == BLOCK)
  • 65. •     a11 a12 a13 a14 1 a21 a22 a23 a24   1  A= a31  R=  a32 a33 a34   1  a41 a42 a43 a44 1
  • 66. ( ) •     a11 a12 a13 a14 1 a21 a22 a23 a24   1  AR =  a31 ×  a32 a33 a34   1  a41 a42 a43 a44 1   a14 a13 a12 a11 a24 a23 a22 a21  =a34  a33 a32 a31  a44 a43 a42 a41
  • 67. ( ) •  T a14 a13 a12 a11 a24 a23 a22 a21  (AR) =  T a34  a33 a32 a31  a44 a43 a42 a41   a14 a24 a34 a44 a13 a23 a33 a43  = a12  a22 a32 a42  a11 a21 a31 a41
  • 68. ( ) •     a11 a12 a13 a14 a41 a31 a21 a11 a21 a22 a23 a24  a42 a32 a22 a12  A= a31  (RA)T =   a32 a33 a34  a43 a33 a23 a13  a41 a42 a43 a44 a44 a34 a24 a14
  • 69. • • R • • •