RStan導入について


RStan導入について

いんとろ

「時系列分析と状態空間モデルの基礎 RとStanで学ぶ理論と実装」の第6部3章で使用するRStanの導入について備忘録(自分用)。

07May'20: Written

導入環境

OS: Mojave (version; 10.14.6)
R version: 3.6.3 (2020-02-29)
R Studio version: 1.2.5033

手順

  1. C++コンパイラの導入
  2. 古いバージョンのRStanを消去
  3. RStanパッケージをダウンロード
  4. 動作確認

C++コンパイラの導入

Stanの実行にC++のコンパイラが必要なので適宜入れる。
CRANのサイトからclang-7.0.0.pkgをダウンロードしてインストールした。
https://cran.r-project.org/bin/macosx/tools/

古いバージョンのRStanを消去

古いバージョンのRStanを消した。
RStudioのコンソールから、以下のコマンドを実行した。

remove.packages("rstan")
if (file.exists(".RData")) file.remove(".RData")

RStanパッケージをダウンロード

以下のコマンドを実行した。

install.packages("rstan", repos = "https://cloud.r-project.org/", dependencies = TRUE)

動作確認

動作確認のため二項分布を描いてみた。

library(rstan)

x <- rbinom(n = 100, size = 20, prob = 0.8)
binomial_test <- "
      data {
      int N;
      int n;
      int x[n];
  }
  parameters {
      real<lower=0, upper=1> p;
  }
  model {
      x ~ binomial(N, p);
  } "
d <- list(N = 20, x = x, n = length(x))
fit <- stan(
      model_code = binomial_test ,
      data= d)

stan_hist(fit)

結果は以下。

上手くかけました。

参照

・Macでrstanの実行環境を用意する
https://sonnamonyaro.hatenablog.com/entry/2019/11/16/092734

・RStan Getting Started
https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started

・Stanを利用した二項分布のパラメーター推定 二項分布
https://stats.biopapyrus.jp/bayesian-statistics/stan/binomial.html