LoginSignup
1
1

More than 3 years have passed since last update.

Rでサイコロシミュレーションしてみた

Last updated at Posted at 2020-02-18

まえがき

Rの勉強を始めたのでアウトプットとしてQiitaに投稿していきます。
初心者の域を出ておりませんのであしからず。

※R version 3.6.2 / RStudio Version 1.2.5033

サイコロシミュレーション

dice.r
dice_function <- function(n){
  dice <- as.integer(runif(n, 1, 7))
  dice.table <- table(dice)
  print(dice.table)
  print(prop.table(dice.table))
  hist(dice,
       breaks=c(0, 1, 2, 3, 4, 5, 6),
       probability=T,
       main="Histogram of 1-6",
       xlab="dice",
       col="gray")
}

メモ

  • runifで一様乱数を発生させるn回、1〜7までの値
  • as.integerで整数値にコンバートしている
  • 関数内でprint文を仕込まないとデバッグできない
  • tableで度数を集計してくれる
  • prop.tableで相対度数にしてくれる
  • hist(plot系共通)にmain, xlab, ylabでラベルを付与できる
  • probability=Tで相対度数で描画できる
  • breaksで幅を指定できる/bins指定だといい感じにやってくれる?
  • c(a, b, c,・・・)はベクトル

コード修正版

※コメント頂きましたので追記します(2020.02.19)
上記コードは教訓として残します
実行結果は修正版に差し替えました

dice.r
dice_function2 <- function(n){
  dice <- sample(6, n, replace=TRUE)
  dice.table <- table(dice)
  print(dice.table)
  print(prop.table(dice.table))
  barplot(prop.table(dice.table),
          main="Barplot of 1-6",
          xlab="dice",
          ylab="probability",
          col="gray")
}

メモ

※コメント引用
- 乱数は,1〜6の整数値を取るので,sample() で求める
- 整数乱数なので,hist() ではなく barplot() で描画する

実行結果

※コード修正版に差し替えました

dice_function2(100)

dice
 1  2  3  4  5  6 
22 20 14  9 15 20 
dice
   1    2    3    4    5    6 
0.22 0.20 0.14 0.09 0.15 0.20 

dice2_100.png

dice_function2(1000)

dice
  1   2   3   4   5   6 
177 169 155 159 162 178 
dice
    1     2     3     4     5     6 
0.177 0.169 0.155 0.159 0.162 0.178 

dice2_1000.png

dice_function2(10000)

dice
   1    2    3    4    5    6 
1703 1687 1594 1669 1649 1698 
dice
     1      2      3      4      5      6 
0.1703 0.1687 0.1594 0.1669 0.1649 0.1698 

dice2_10000.png

dice_function2(100000)

dice
    1     2     3     4     5     6 
16762 16645 16593 16580 16656 16764 
d
ice
      1       2       3       4       5       6 
0.16762 0.16645 0.16593 0.16580 0.16656 0.16764 

dice2_100000.png

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