偽隨機數生成

R 的抽樣

Richie Cotton

Data Evangelist at DataCamp

什麼是隨機?

{adjective} 地製作、執行、發生或選擇,且沒有方法或有意識的決定。

  • 牛津語言辭典
R 的抽樣

真隨機數

  • 來源於物理過程,如擲硬幣。
  • Hotbits 使用放射性衰變。
  • RANDOM.ORG 使用大氣雜訊。
    • 在 R 可透過 random 套件使用。
  • 真隨機成本高。
1 https://www.fourmilab.ch/hotbits 2 https://www.random.org
R 的抽樣

偽隨機數生成

  • 下一個「隨機」數由前一個「隨機」數計算得出。
  • 第一個「隨機」數由一個種子計算而來。
  • 若從相同種子開始,之後的隨機數都會相同。
seed <- 1
calc_next_random(seed)
3
calc_next_random(3)
2
calc_next_random(2)
6
R 的抽樣

隨機數生成函式

function distribution function distribution function distribution
rbeta Beta rgeom Geometric rsignrank Wilcoxon signed rank
rbinom Binomial rhyper Hypergeometric rt t
rcauchy Cauchy rlnorm Lognormal runif Uniform
rchisq Chi-squared rlogis Logistic rweibull Weibull
rexp Exponential rnbinom Negative binomial rwilcox Wilcoxon rank sum
rf F rnorm Normal
rgamma Gamma rpois Poisson
R 的抽樣

視覺化隨機數

rbeta(5000, shape1 = 2, shape2 = 2)
[1] 0.2788 0.7495 0.6485 0.6665 0.6546 0.1575
...

[4996] 0.84719 0.35177 0.92796 0.67603 0.53960
randoms <- data.frame(
  beta = rbeta(5000, shape1 = 2, shape2 = 2)
)
ggplot(randoms, aes(beta)) +
  geom_histogram(binwidth = 0.1)

beta 直方圖

R 的抽樣

隨機數的種子

set.seed(20000229)
rnorm(5)
-1.6538 -0.4028 -0.1654 -0.0734  0.5171
rnorm(5)
1.908  0.379 -1.499  1.625  0.693
set.seed(20000229)
rnorm(5)
-1.6538 -0.4028 -0.1654 -0.0734  0.5171
rnorm(5)
1.908  0.379 -1.499  1.625  0.693
R 的抽樣

使用不同種子

set.seed(20000229)
rnorm(5)
-1.6538 -0.4028 -0.1654 -0.0734  0.5171
rnorm(5)
1.908  0.379 -1.499  1.625  0.693
set.seed(20041004)
rnorm(5)
-0.6547 -0.7854 -0.0152  0.1514  0.5285
rnorm(5)
0.748  0.974  0.174 -0.781 -0.930
R 的抽樣

一起來練習吧!

R 的抽樣

Preparing Video For Download...