LoginSignup
2
2

More than 3 years have passed since last update.

MCMCのためのRStan環境構築 [mac, JupyterLab]

Posted at

目的

  • 確率的プログラミング言語であるStanをRから利用するためのライブラリである「RStan」をインストールします。

動作確認環境

  • macOS Big Sur (version 11.1)
  • Jupyter Core : 4.6.3
  • Jupyter Lab : 2.2.8
  • R : 4.0.3

前提条件

  • Rがインストールされていること

JupyterLab環境へのRのインストール手順についてはこちらにまとめています。

インストール手順

基本的には公式リポジトリに記載されている手順に従います。
ただし本記事では、RStudioやRコンソールではなく、JupyterLabのRカーネル上で実行・動作確認しています。

JupyterLabを起動し、Rカーネルを起動します。

% jupyter lab

0. 古いRStanの削除

古いRStanがインストールされている場合には安全のため、以下の手順で既存のRStanパッケージを削除した方がよい場合があります。必要な場合のみ実施してください。

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

1. RStanのインストール

以下を実行することでRStanライブラリをインストールできます。

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

筆者の環境で起きたエラーの回避策を示しておきます。

【回避策1】 依存ライブラリ igraph のインストールエラー

macOSのバージョンに起因するclang errorが発生しました。
XCodeを再インストールすることで回避できました。

% sudo rm -rf /Library/Developer/CommandLineTools
% sudo xcode-select --install

【回避策2】 依存ライブラリ V8 のインストールエラー

v8.h がないからインストールできない、というエラーが発生しました。
HomebrewでV8をインストールすることで回避できました。

% brew install v8

2. C++コンパイラ

C++コンパイラがインストールされているかチェックするため、以下を実行します。
インストールされていれば TRUE が返ってきます。

In
pkgbuild::has_build_tools(debug = TRUE)
# TRUE

3. インストールの確認

正常にインストールされていれば、次を実行することで以下のような出力が得られます。

In
library(rstan)
Out
Loading required package: StanHeaders

Loading required package: ggplot2

rstan (Version 2.21.2, GitRev: 2e1f913d3ca3)

For execution on a local, multicore CPU with excess RAM we recommend calling
options(mc.cores = parallel::detectCores()).
To avoid recompilation of unchanged Stan programs, we recommend calling
rstan_options(auto_write = TRUE)

参考

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2