準備と動作確認 Preparation 〜RstudioでC++を覚える

  • Rをインストール Install R
  • Rstudioをインストール Install Rstudio
  • RstudioのツールバーメニューからC++ファイルを新規作成、とすると、もしコンパイラとかの準備がまだだったらdevtoolsとかのインストールをするかどうか訊いてきてくれるので、それにしたがうのもよい
  • Rstudioを立ち上げる Start Rstudio
  • これも
  • これも
  • RコンソールでRcppパッケージをインストールして読み込み Install Rcpp package and load it in the R console panel of Rstudio.
install.packages("Rcpp")
library(Rcpp)
  • Rstudioでc++ファイルを作る Make a c++ file with Rstudio.
    • RstudioのツールバーからC++ファイルを新しく作る、にするとパネルが開くので、最初はサンプルをそのまま貼る (こちら) Go to Rstudio's toolbar and select "make a new c++ file" and paste sample codes into it.
    • "gibbs.cpp"という名前で保存する(ワーキングディレクトリに) Save it "gibbs.cpp" in your working directory.
#include <Rcpp.h>
using namespace Rcpp;
 
// [[Rcpp::export]]
NumericMatrix gibbs(int N, int thin) {
 
   NumericMatrix mat(N, 2);
   double x = 0, y = 0;
 
   RNGScope scope;
   for(int i = 0; i < N; i++) {
      for(int j = 0; j < thin; j++) {
         x = R::rgamma(3.0, 1.0 / (y * y + 4));
         y = R::rnorm(1.0 / (x + 1), 1.0 / sqrt(2 * x + 2));
      }
      mat(i, 0) = x;
      mat(i, 1) = y;
   }
 
   return(mat);
}
  • RstudioのRコンソールに戻って Go back to R console in Rstudio then,
# c++ファイルを読み込んで
sourceCpp("gibbs.cpp")
# c++ファイルに作ってあるgibbs()という関数を使う
gibbs(10,10)
  • こうなる You are seeing this