LoginSignup
3
3

Rでの並列計算

Last updated at Posted at 2024-03-13

Rで並列計算を頻繁に行うのですが、その度に「あれ、どうやるんだっけ」となるので、備忘録として方法を記しておきます。
いくつか並列計算の方法があるようですが、自分はdoParallelパッケージのforeachで実行しています。

コード

library(doParallel)

# 1
cores <- 10 # No. of cores to be used

# 2
cl <- makeCluster(cores)
registerDoParallel(cl)

# 3
result <- foreach(i = 1:100) %dopar% { 
    # calculation
}

# 4
stopCluster(cl)

コードの内容

  1. 並列計算の数(使用するコア数)を決める
  2. 1で定めた数のスレッドを確保する
  3. foreach内で定めた範囲(上の例だと i = 1 ~ 100)で、%dopar%以降の中身を並列・繰り返し計算し、その結果をresultに入れる
  4. 並列化を終了し、コアを開放する

result はlist形式のオブジェクトとして作られる。要素数は総計算数(上の例だと100)であり、各要素に各計算結果が収まっている。

3
3
0

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
3
3