404 Not Found

404 Not Found


nginx

Rによる確率分布:正規分布、二項分布、ポアソン分布の完全チュートリアル

前回のレッスンでは、「データの分析」――つまり記述統計――について学びました。今回のレッスンでは、「ランダム性の分析」――確率分布――について学びます。R におけるすべての統計的推論(t 検定、回帰分析、仮説検定)は、確率分布に基づいています。今回のレッスンでは、R の d/p/q/r 4つの主要な関数群と、よく使われる4つの分布について解説します。

このレッスンを修了すると、R を使ってあらゆるランダムな現象をシミュレーションしたり、確率計算を行ったりできるようになり、今後の仮説検定に向けた基礎を築くことができます。

1. 学習内容



2. 品質検査に関するエピソード

(1) 課題:製品の合格率は通常どの程度か?

アリスは品質管理検査員で、ある生産ラインの製品の平均重量が100g、標準偏差が2gであることを突き止めました。上司は彼女に、「95g未満の製品の割合はどれくらいか?」と尋ねました。

本で正規分布の表を調べる? Excelの関数を使う? それとも、たった1行のRコードで――

(2) Rを用いた解決策

R
# Weight < 95g the probability
pnorm(95, mean = 100, sd = 2)
# [1] 0.00621  ← 0.6%

# Extract 1000 Product Simulation Testing
set.seed(42)
samples <- rnorm(1000, mean = 100, sd = 2)
mean(samples < 95)  # 0.6%  ← Verification

2行のコード → 解答 + シミュレーションによる検証



3. Rにおける確率分布関数の4つの主要な分類

(1) 4つの主要機能の比較

関数接頭辞 意味 目的
d 密度 確率密度関数 (PDF)
p 確率 累積分布関数 (CDF)
q 分位数 逆関数(確率から分位数を求める)
r ランダム 乱数を生成する

すべての分布には、次の4つの関数があります:dnorm pnorm qnorm rnorm(正規分布);dbinom pbinom…(二項分布)、など。

(2) 記憶のヒントとなるフレーズ

100%
graph LR
    A[d Density] -->|Find the probability| B[p Cumulative]
    B -->|Inverse Quantile| C[q quantile]
    A -->|Simulation| D[r Random]
    
    style A fill:#cce5ff
    style B fill:#d4edda
    style C fill:#f8d7da
    style D fill:#fff3cd

(3) 4つの主要な機能に関する詳細な説明

R
# Take the normal distribution as an example (Mean 0, Standard Deviation 1)
dnorm(0)             # 0.3989  ← Probability Density
pnorm(0)             # 0.5     ← Cumulative Probability
qnorm(0.975)         # 1.96    ← Given that 97.5% Find the percentile
rnorm(5)             # 5 A random number

# Custom Parameters (Mean 100, Standard Deviation 2)
dnorm(95, 100, 2)    # 95 Density at that point
pnorm(95, 100, 2)    # 95 Left-sided cumulative probability
qnorm(0.975, 100, 2) # Given that 97.5% Find the percentile
rnorm(5, 100, 2)     # 5 Per capita average 100 Random Number


4. 正規分布(最も一般的に使用される)

(1) 正規分布とは何ですか?

100%
graph TB
    A[Normal Distribution N mu sigma] --> B[Bell-shaped symmetry]
    A --> C[68-95-99.7 Principles]
    A --> D[Central Limit Theorem]
    A --> E[Widely found in nature/Social Phenomena]
    
    style A fill:#fff3cd
    style B fill:#cce5ff
    style C fill:#d4edda
    style D fill:#f8d7da
    style E fill:#e1d4ff

正規分布 = ベル型で対称であり、自然界で最もよく見られる分布である。

(2) 68-95-99.7のルール

R
μ ± 1σ → 68.27% Data
μ ± 2σ → 95.45% Data
μ ± 3σ → 99.73% Data

(3) 4つの標準正規関数

R
# Standard Normal N(0, 1)
dnorm(0)              # 0.3989
pnorm(1.96)           # 0.975  ← 1.96 On the left 97.5%
qnorm(0.975)          # 1.96   ← 97.5% quantile = 1.96
rnorm(5)              # 5 A standard normal random number

# General Normal N(μ, σ)
mu <- 100
sigma <- 2

# P(X < 95) = ?
pnorm(95, mean = mu, sd = sigma)  # 0.00621

# P(95 < X < 105) = ?
pnorm(105, mu, sigma) - pnorm(95, mu, sigma)  # 0.9876

# 99% Data Range
qnorm(0.005, mu, sigma)  # The Lower World
qnorm(0.995, mu, sigma)  # Upper Realm

(4) 正規性の検定

R
# 1. Visual: QQ plot
qqnorm(x)
qqline(x, col = "red")

# 2. Statistical Tests
shapiro.test(x)       # Shapiro-Wilk (n < 5000)
# p < 0.05 Indicates non-normal distribution


5. 二項分布(成功/失敗)

(1) 二項分布とは何ですか?

n回の独立したベルヌーイ試行における成功回数の分布。各試行における成功確率はp、失敗確率は1-pである。

R
Example: Toss 10 coins, number of times facing up X ~ Binomial(10, 0.5)

(2) 4つの主要な二項関数

R
# Toss 10 coins, number of heads
dbinom(5, size = 10, prob = 0.5)    # 0.246  <- P(5 heads)
pbinom(5, size = 10, prob = 0.5)    # 0.623  <- P(<= 5 heads)
qbinom(0.5, size = 10, prob = 0.5)   # 5      ← Median
rbinom(1000, size = 10, prob = 0.5) # 1000 sets of 10 trials, number of successes each

# Example: 100 shots, hit rate 80%, probability of at least 90 hits
1 - pbinom(89, size = 100, prob = 0.8)
# [1] 0.0227  ← 2.3%

(3) 二項分布の可視化

R
n <- 10
p <- 0.5
x <- 0:n

# Probability Mass Function
plot(x, dbinom(x, n, p), type = "h",
     main = paste0("Binomial(", n, ",", p, ")"),
     xlab = "Number of Successes", ylab = "Probability",
     col = "blue", lwd = 2)
points(x, dbinom(x, n, p), pch = 19, col = "red")


6. ポアソン分布(事象の数)

(1) ポアソン分布とは何ですか?

特定の時間または空間内で発生する事象の数の分布。一般的に以下の用途に使われる:

パラメータ λ は、単位時間あたりの事象の平均回数である。

(2) 4つのポアソン関数

R
# Example: Average 10 customers per hour
dpois(8, lambda = 10)    # P(X = 8) = 0.1126
ppois(8, lambda = 10)    # P(X ≤ 8) = 0.3328
qpois(0.5, lambda = 10)  # Median = 10
rpois(100, lambda = 10)  # 100 Number of customers visiting the store per hour

# Example: 5 complaints per day, probability of more than 10
1 - ppois(10, lambda = 5)  # 0.0137  ← 1.4%

(3) ポアソン分布と正規分布の関係

λが大きい場合、ポアソン分布は正規分布に近似される N(λ, √λ)

R
# λ = 100
lambda <- 100
# Poisson P(90 ≤ X ≤ 110)
ppois(110, lambda) - ppois(89, lambda)  # ≈ 0.728

# Equivalent Normal Approximation
pnorm(110, 100, 10) - pnorm(90, 100, 10)  # ≈ 0.683
# Approximate but not exactly equal


7. t分布/F分布/カイ二乗分布

(1) 3つの主要な標本分布のクイックリファレンス

分布 用途 R関数
t分布 小標本における平均の推定 dt/pt/qt/rt
F分布 分散分析(ANOVA) df/pf/qf/rf
カイ二乗分布 カテゴリ変数、適合度 dchisq/pchisq/qchisq/rchisq

(2) t分布の詳細な解説

R
# Degrees of freedom df = 10
qt(0.975, df = 10)   # 2.228  <- t threshold (larger than the normal distribution's 1.96)
pt(2.228, df = 10)    # 0.975

# As df -> inf, t distribution -> standard normal
qt(0.975, df = 1000)  # 1.962  ← Approach 1.96
qt(0.975, df = 10000) # 1.960
💡 ヒント:n > 30 の場合、t 分布は正規分布とほぼ同一であるため、正規近似を使用できます。n < 30 の場合は、厳密に t 分布を使用してください。

(3) カイ二乗分布

R
# Degrees of freedom df = 5
dchisq(3, df = 5)   # Density
pchisq(11.07, df = 5)  # 0.95  <- Chi-square critical value (95%)
qchisq(0.95, df = 5)   # 11.07

# Example: Observed 8 events, expected 5, p-value
1 - pchisq(8, df = 5)  # 0.846

(4) F分布

R
# Degrees of freedom df1 = 5, df2 = 10
qf(0.95, df1 = 5, df2 = 10)  # 3.326  ← F Threshold
pf(3.326, df1 = 5, df2 = 10) # 0.95


8. set.seed: 乱数シード

(1) なぜ種が必要なのでしょうか?

Rの「乱数」は、実際には擬似乱数です。シードが与えられれば、結果は再現可能です:

R
# No seeded players
rnorm(3)  # The results are different every time

# Let $s$ be a seed
set.seed(42)
rnorm(3)  # The First Time
set.seed(42)
rnorm(3)  # Exactly the same
💡 ヒント研究や報告書には必ず set.seed() を記載してください。これにより、結果の再現性が確保されます。

(2) 実用例

R
# 1. Simulate Preset Seeds
set.seed(42)
sim_data <- rnorm(1000, 100, 15)

# 2. Set a seed before training the model
set.seed(123)
model <- lm(y ~ x, data)

# 3. Set a seed before cross-validation
set.seed(2024)
folds <- createFolds(data$y, k = 5)


9. サンプリングとシミュレーション

(1) sample() サンプリング

R
# 1. Simple Random Sampling
sample(1:100, 10)            # Draw 10 from 1-100 (no duplicates)
sample(1:100, 10, replace = TRUE)  # Sampling with replacement

# 2. Data Frame Sampling
sample_n(df, 10)              # Draw 10 rows (old)
slice_sample(df, n = 10)      # Draw 10 rows (dplyr 1.0+)

# 3. Stratified Sampling
df |>
  group_by(class) |>
  slice_sample(n = 5)         # Draw one from each group 5 row

# 4. Set Up Probability Sampling
sample(c("A", "B", "C"), 100, replace = TRUE,
       prob = c(0.5, 0.3, 0.2))

(2) モンテカルロ法

R
# Example: Estimate pi
set.seed(42)
n_sim <- 100000
x <- runif(n_sim, -1, 1)
y <- runif(n_sim, -1, 1)
inside <- sqrt(x^2 + y^2) <= 1
pi_est <- 4 * mean(inside)
# [1] 3.14116  ← Approach π = 3.14159


10. 完全な例:品質検査のシミュレーション

以下は、このレッスンで取り上げた確率分布に関するすべての概念を結びつけた完全なワークフローの例です。

▶ サンプル:生産ラインにおける品質検査のシミュレーション

R
# ============================================
# Production Line Quality Inspection Simulation
# Features: Comprehensive Application of 4 Distributions
# ============================================

set.seed(42)

# 1. Product Weight Inspection (Normal Distribution)
# Specifications: Mean 100g, Standard Deviation 2g
n_products <- 10000
weights <- rnorm(n_products, mean = 100, sd = 2)

cat("=== Weight Inspection (Normal Distribution N(100, 2)) ===\n")
cat("Sample size:", length(weights), "\n")
cat("Actual Mean:", round(mean(weights), 4), "\n")
cat("Actual standard deviation:", round(sd(weights), 4), "\n")
cat("Theory < 95g Ratio:", round(pnorm(95, 100, 2), 4), "\n")
cat("Actual < 95g Ratio:", round(mean(weights < 95), 4), "\n")
cat("Theory < 105g Ratio:", round(pnorm(105, 100, 2), 4), "\n")
cat("Actual < 105g Ratio:", round(mean(weights < 105), 4), "\n\n")

# 2. Inspection of Nonconforming Products (Binomial Distribution)
# Sample 100 items, probability of at least 95 passing
n_sample <- 100
p_pass <- 0.95
prob_at_least_95 <- 1 - pbinom(94, n_sample, p_pass)
cat("=== Random Sampling Inspection (Binomial(100, 0.95)) ===\n")
cat("P(95 Qualified) =", round(prob_at_least_95, 4), "\n\n")

# 3. Customers Visit the Store (Poisson Distribution)
# Average 10 customers per hour
n_hours <- 1000
customers <- rpois(n_hours, lambda = 10)
cat("=== Customers Visit the Store (Poisson(10)) ===\n")
cat("Theoretical mean: 10\n")
cat("Actual Mean:", round(mean(customers), 2), "\n")
cat("Theory P(>15):", round(1 - ppois(15, 10), 4), "\n")
cat("Actual P(>15):", round(mean(customers > 15), 4), "\n\n")

# 4. Sample Survey (t Distribution)
# Sample 30 products, estimate mean
sample_size <- 30
sample_data <- sample(weights, sample_size)
cat("=== Sample Survey (t Distribution) ===\n")
cat("Sample size:", sample_size, "\n")
cat("Sample mean:", round(mean(sample_data), 2), "\n")
cat("95% Confidence Interval: [\n")
ci <- t.test(sample_data)$conf.int
cat("  ", round(ci[1], 2), ",", round(ci[2], 2), "]\n\n")

# 5. Hypothesis Testing (use qnorm)
# I want to know if the weight deviates significantly 100g
z_score <- (mean(sample_data) - 100) / (sd(sample_data) / sqrt(sample_size))
p_value <- 2 * (1 - pnorm(abs(z_score)))
cat("=== Hypothesis Testing (Z Test) ===\n")
cat("Z score:", round(z_score, 4), "\n")
cat("P value:", round(p_value, 4), "\n")
cat("Conclusion:", ifelse(p_value < 0.05, "Significant deviation from 100g", "No significant difference"), "\n\n")

# 6. Outlier Detection (The Concept of the Chi-Square Distribution)
# Use 3-sigma principle
outliers <- weights[abs(weights - 100) > 3 * 2]
cat("=== Outlier Detection (3-sigma Principle) ===\n")
cat("Theoretical Anomaly Ratio:", round(2 * pnorm(-3), 6), "(i.e. 0.27%)\n")
cat("Actual Number of Exceptions:", length(outliers), "/", n_products, "\n")
cat("Actual Exception Rate:", round(length(outliers) / n_products, 6), "\n")

# 7. Sampling Design (Stratified Sampling)
cat("\n=== Stratified Sampling ===\n")
# Simulate 3 production lines (Different Pass Rates)
production <- tibble::tibble(
  line = rep(c("Line A", "Line B", "Line C"), each = 1000),
  weight = c(rnorm(1000, 100, 2),
             rnorm(1000, 101, 2),
             rnorm(1000, 99, 2))
)

# Draw 50 from each line
library(dplyr)
sampled <- production |>
  group_by(line) |>
  slice_sample(n = 50)

cat("Draw 50 per line, Estimated Overall Mean:\n")
cat("Overall Sample Mean:", round(mean(sampled$weight), 2), "\n")
cat("Total True Mean:", round(mean(production$weight), 2), "\n")
▶ 試してみよう

期待される出力(抜粋):

R
=== Weight Inspection (Normal Distribution N(100, 2)) ===
Sample size: 10000
Actual Mean: 99.9898
Actual standard deviation: 1.9973
Theory < 95g Ratio: 0.0062
Actual < 95g Ratio: 0.0063

=== Random Sampling Inspection (Binomial(100, 0.95)) ===
P(95 Qualified) = 0.5647

❓ よくある質問

Q d、p、q、r をどのように区別しますか?
A d は密度(density)、p は累積(cumulative)、q は分位数(quantile)、r はランダム(random)を表します。
Q QQノルムプロットはどのように解釈すればよいですか?
A 赤い線に近い点は正規分布を示しています。S字型の曲線は偏った分布を示し、U字型の曲線は重尾分布または軽尾分布を示します。
Q カイ二乗分布は何に使われますか?
A ① 適合度検定 ② 独立性の検定(分割表) ③ 推定分散の信頼区間。このレッスンでは詳しく説明しませんが、次のレッスンで取り上げる仮説検定で用いられます。

📖 まとめ


📝 練習問題

  1. 基本問題pnorm を使用して、N(100, 2) 分布について、① P(X < 95)、② P(X > 105)、③ P(95 < X < 105)、および ④ 99% 信頼区間を計算しなさい。結果を確認しなさい。

  2. 基本問題rbinom(1000, 10, 0.5) を使用して、「コインを10回投げる」実験を1,000回シミュレーションし、標本の平均、分散、標準偏差を算出せよ。これらの値を理論値(5、2.5、1.58)と比較せよ。

  3. 基本問題rpois(1000, 5) を使用して、「5分以内に受信した通話数」のシミュレーションを1,000回行い、ヒストグラムと理論上のポアソン分布の確率密度関数(PDF)をプロットし、両者の分布を比較する。

  4. 応用問題:10,000個の製品重量(正規分布 N(100, 2))をシミュレーションし、3σの法則を用いて外れ値の数を特定し、その値を理論値である0.27%と比較して、中心極限定理(CLT)を検証する。

  5. 課題:モンテカルロ法を用いてπを推定する:① サイコロを10,000回振る;② 1/4円内に止まった回数の割合を計算する; ③ この割合の4倍=πと推定する;④ サイコロを振る回数(100回、1,000回、10,000回、100,000回)を変えて、精度の変化を観察する。4つの精度レベルにおける結果のスクリーンショットを撮影する。

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%