연속형 확률분포 (Continuous probability distribution)에는

 

 - 정규분포 (normal distribution)

   : norm()

 

 - 균등분포 (uniform distribution)

   : unif()

 

 - 지수분포 (exponential distribution)

   : exp()

 

 - t-분포 (t-distribution)

   : t()

 

 - F-분포 (F-distribution)

   : f()

 

 - 카이제곱분포(chisq-distribution)

   : chisq()

 

등이 있습니다.  

 

 

이번 포스팅에서는 지수분포 (exponential distribution)에 대해서 소개하도록 하겠습니다.  지수분포 (exponential distribution)는 어떤 특정 사건이 발생하기 전까지 걸리는 시간을 나타내기 위해 많이 사용하는 확률분포 입니다. 

 

지수분포(exponential distribution)의 예로는 전자레인지의 수명시간, 콜센터에 전화가 걸려 올 때까지 걸리는 시간, 경부고속도로 안성나들목에서 다음번 교통사고가 발생할 때까지 걸리는 시간, 은행 지점에 고객이 내방하는데 걸리는 시간 등이 있겠습니다.

 

참고로, 이산형 확률분포 중에서 포아송 분포 (Poisson distribution)이 단위 시간 혹은 단위 공간에서 특정 사건이 발생하는 횟수에 대한 분포를 나타낼 때 주로 사용한다고 했는데요, 헷갈리지 않도록 주의를 해야겠습니다.

 

 

 

확률변수 X의 확률밀도함수가 위와 같을 때, 확률변수 X는 모수 λ인 지수분포를 따른다고 말합니다.

 

R에서 지수분포(exponential distribution)와 관련된 함수 및  파라미터는 다음과 같습니다.

 

 함수 구분

지수분포 함수/파라미터 

 exp()

 밀도 함수
 (Density function)

 d

  dexp(x, rate)

 누적분포 함수

 (Cumulative distribution function)

 p

  pexp(q, rate, lower.tail=TRUE/FALSE)

 분위수 함수

 (Quantile function)

 q

  qexp(p, rate, lower.tail=TRUE/FALSE)

 난수 생성

 (Random number generation)

 r

  rexp(n, rate)

 

 

(1) 지수분포 그래프 (Exponential distribution plot) : fun=dexp

 

 
> library(ggplot2)

> # (1) 지수분포 그래프 (Exponential distribution plot) : fun=dexp > ggplot(data.frame(x=c(0,10)), aes(x=x)) + + stat_function(fun=dexp, args=list(rate=1), colour="brown", size=1.5) + + ggtitle("Exponential Distribution") > + ggtitle("Exponential Distribution")

 

 

 

 

 

(2) 누적 지수분포 그래프 (Cumulative exponential distribution plot) : fun = pexp

 

 

> # (2) (Cumulative exponential distribution plot) : fun=pexp > ggplot(data.frame(x=c(0,10)), aes(x=x)) + + stat_function(fun=pexp, args=list(rate=1), colour="brown", size=1.5) + + ggtitle("Cumulative Exponential Distribution")

 

 

 

 

(3) 누적 지수분포 확률 값 계산 : pexp(q, rate, lower.tail=TRUE/FALSE)

 

 

 
> pexp(q=2, rate=1, lower.tail = TRUE)
[1] 0.8646647
 

 

λ (rate) = 1 인 지수분포에서 0~1까지의 누적 확률 값은 0.8646647 임을 알 수 있습니다.  

 

 

(4) 지수분포 분위수 함수 값 계산 : qexp(p, rate, lower.tail=TRUE/FALSE)

 

 

> qexp(p=0.8646647, rate=1, lower.tail = TRUE)
[1] 2
 

 

 

qexp()는 pexp()와 역의 관계에 있다고 보면 되겠습니다.

 

 

(5) 지수분포 난수 발생 (exponential distribution random number generation) : rexp(n, rate)

 

 

> rexp(100, rate=1)
  [1] 0.805385854 1.077017598 0.941678341 2.059229603 0.517943248 0.955476408 0.575837716
  [8] 0.851462637 0.086982322 1.243358626 1.077268675 2.604957888 0.007571515 1.793674221
 [15] 0.118729103 0.096055712 0.015758928 0.201158101 0.914114063 0.130984491 2.752139235
 [22] 0.829986667 0.651976457 1.265562156 2.635988993 1.190808342 0.444055191 1.480476206
 [29] 1.741018226 2.692880185 0.804053361 3.127147071 0.902618388 1.432761851 0.369694262
 [36] 0.290926187 0.576759913 0.827636680 1.634353038 2.113214617 0.570110160 0.609782309
 [43] 1.985241502 1.067016441 0.098556668 3.326005637 2.261946740 6.395236475 1.906314444
 [50] 0.503994692 1.578938061 0.144050682 0.361734510 1.495605791 1.167056286 1.397221429
 [57] 1.598533234 0.370363955 0.153343928 0.351399011 0.957647500 1.053767695 0.272256882
 [64] 1.176451771 0.222995248 1.125289913 0.076051627 3.489328747 0.199440748 3.143880822
 [71] 1.640546855 4.492400575 1.102261695 0.189814932 0.222941682 2.305212835 0.069710370
 [78] 1.972949872 0.201703040 1.783014953 1.297271054 2.173743544 2.350792197 2.018307233
 [85] 0.417343667 2.533255698 0.522270208 2.068958899 1.062778262 0.210765630 0.804149691
 [92] 1.261281259 0.006859250 0.620238345 3.478939042 2.692230696 0.557543887 1.830330845
 [99] 0.478452368 0.904496278
> hist(rexp(100, rate=1), breaks=10)
 

 

 

 

 

(6) dexp(x, rate, log=TRUE)

 

log=TRUE 옵션을 설정하면 지수분포의 확률밀도함수값에 밑이 e (약 2.17)인 자연로그 ln 을 취한 값을 계산합니다. (참고 : 자연로그인 ln 의 역함수는 지수함수인 exp() )

 

아래에는 X가 모수 λ가  1인 지수분포를 따른다고 했을 때, X: 1, 2, .., 10 의 확률밀도함수값을 계산한 것입니다.  (지수분포는 연속형 확률분포이지만, log 취한거와 비교를 이해하기 쉽도록 1, 2, ..., 10 의 값을 가지고 계산했음)  'log=TRUE' 라는 옵션을 취한 값과, log(dexp) 라는 수식을 직접 입력해서 계산한 값이 서로 정확히 일치함을 알 수 있습니다.

 

> # dexp(x, rate, log=TRUE)
> dexp <- dexp(c(1:10), rate=1)
> dexp_log <- dexp(c(1:10), rate=1, log=TRUE)
> 
> exp_df <- data.frame(cbind(c(1:10), dexp, dexp_log))
> exp_df
   V1         dexp dexp_log
1   1 3.678794e-01       -1
2   2 1.353353e-01       -2
3   3 4.978707e-02       -3
4   4 1.831564e-02       -4
5   5 6.737947e-03       -5
6   6 2.478752e-03       -6
7   7 9.118820e-04       -7
8   8 3.354626e-04       -8
9   9 1.234098e-04       -9
10 10 4.539993e-05      -10
> 
> exp_df <- transform(exp_df, dexp_logarithm = log(dexp))
> exp_df
   V1         dexp dexp_log dexp_logarithm
1   1 3.678794e-01       -1             -1
2   2 1.353353e-01       -2             -2
3   3 4.978707e-02       -3             -3
4   4 1.831564e-02       -4             -4
5   5 6.737947e-03       -5             -5
6   6 2.478752e-03       -6             -6
7   7 9.118820e-04       -7             -7
8   8 3.354626e-04       -8             -8
9   9 1.234098e-04       -9             -9
10 10 4.539993e-05      -10            -10

 

 

 

 

디폴트인 dexp(x, log=FALSE) 와 dexp(x, log=TRUE) 옵션 설정해서 나온 값을 가지고 그래프로 그려서 비교해보면 아래와 같습니다.  log=TRUE 설정을 해서 자연로그를 취했더니 원래 밑으로 축 쳐졌던 지수분포 그래프가 곧은 직선으로 변환되었음을 알 수 있습니다.

 

> my_par = par(no.readonly = TRUE)
> par(oma = c(0, 0, 1, 0))
> par(mfrow = c(1, 2))
> 
> plot(dexp, main = "dexp : log = F")
> plot(dexp_log, main = "dexp : log = T")
> 
> mtext("density function of exponential distributin : log = FALSE vs. log = TRUE", 
outer = TRUE, cex = 1.2)

 

 

 

 많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡'를 꾸욱 눌러주세요.

 

728x90
반응형
Posted by Rfriend
,

통계에서 빼놓을 수 없는 기본 개념 중의 하나가 확률입니다.  모집단에서 표본을 추출할 때 랜덤 샘플링, 층화 랜덤 샘플링 등과 같이 확률을 사용합니다.  추정과 검정에서도 확률분포를 사용합니다.  회귀분석, 판별분석 등에서도 변수가 정규분포를 따르고 있는지 검정합니다.  시뮬레이션을 할 때 모집단의 확률분포에 따라 난수를 발생시키기도 합니다.

 

특히, 통계를 좀 공부했던 분이라면 정규분포는 알고 있을 듯 합니다.  하지만, 그 외에 분포들은 들어는 봤어도 모양이 어떻게 생겼는지, 어떤 때 사용하는 것인지 정확히 모르고 있는 경우가 더 많을 듯 합니다.

 

R ggplot2를 활용해서 연속확률분포 곡선을 그려보면 분포별로 모양을 이해하는데 도움이 되겠지요.  그리고 모수에 따라서 모양이 어떻게 바뀌는지도 확인해 볼 수 있겠구요.

 

이번 포스팅에서는 주로 'd'로 시작하는 밀도 함수 (Density Function) 에 대해서 정규분포(norm), t-분포(t), 카이제곱분포(chisq), 지수분포(exp), F분포(f), 감마분포(gamma), 균등분포(unif) 등의 분포에 대해서 ggplot2로 그리는 방법을 소개해보겠습니다. 

 

 

[ 연속확률분포 종류별 / 함수 종류별 ggplot2 그리기 함수 종합표 ]

 

분포 

밀도 함수

d

누적분포 함수

p

분위수 함수 

q

난수 발생 

r

정규분포 

 norm()

 dnorm()

 pnorm()

qnorm()

rnorm() 

 t-분포

 t()

 dt()

 pt()

qt() 

rt() 

카이제곱분포 

 chisq()

 dchisq()

 pchisq()

qchisq() 

rchisq() 

 지수분포

exp() 

 dexp()

 pexp()

qexp() 

rexp() 

 F분포

 f()

 df()

 pf()

qf() 

rf() 

 감마분포

 gamma()

 dgamma()

 pgamma()

qgamma()

rgamma() 

균등분포 

 unif()

 dunif()

 punif()

qunif() 

runif() 

 

 

ggplot2는 별도의 설치 및 호출이 필요한 패키지이므로 아래의 절차를 먼저 실행합니다.

 

> install.packages("ggplot2")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/ggplot2_1.0.1.zip'
Content type 'application/zip' length 2676292 bytes (2.6 MB)
downloaded 2.6 MB

package ‘ggplot2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\RtmpGAPkIo\downloaded_packages
> library(ggplot2) 

 

 

(1) 정규분포 활률밀도곡선 (Normal Distribution Probability Density Curve)

    : stat_function(fun = dnorm)

 

> # 정규분포 : fun = dnorm
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dnorm, colour="blue", size=1) +
+   ggtitle("Normal Distribution")

 

 

 

 

 

 

(2) 정규분포의 특정 구간에만 색깔 넣기 (colour at specific range of normal distribution)

 

> # 함수 특정 구간에 색깔 넣기
> dnorm_range <- function(x) {
+   y <- dnorm(x) 
+   y[x < -1 | x > 2] <- NA  # 이 범위에는 색깔 없음
+   return(y)
+ }
> 
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dnorm, colour="blue", size=1) +
+   stat_function(fun=dnorm_range, geom="area", fill="grey", alpha=0.5) + 

+ ggtitle("Normal Distribution of x~N(0,1) with colour from -1 to 2")

 

 

 

 

 

(3) 누적정규분포 (Cummulative Normal Distribution) : stat_function(fun = pnorm)

 

> # 누적정규분포 : fun = pnorm
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=pnorm, colour="black", size=1.5) +
+   ggtitle("Cumulative Normal Distribution of x~N(0,1)")

 

 

 

 

 

 

(4) 정규분포 : 평균과 분산 지정 (Normal Distribution with specific mean and standard deviation) : stat_function(fun = dnorm, args=list(mean=2, sd=1))

 

> # 정규분포: 평균과 분산 지정
> ggplot(data.frame(x = c(-5, 5)), aes(x=x)) +
+   stat_function(fun=dnorm, args=list(mean=2, sd=1), colour="black", size=1.5) +
+   geom_vline(xintercept=2, colour="grey", linetype="dashed", size=1) + # 평균에 세로 직선 추가
+   geom_text(x=0, y=0.3, label="x = N(2, 1)") +
+   ggtitle("Normal Distribution of x~N(2,1)")

 

 

 

 

 

 

(5) t-분포 (t-Distribution) : stat_function(fun = dt)

 

> # t-분포 : fun = dt 
> ggplot(data.frame(x=c(-3,3)), aes(x=x)) +
+   stat_function(fun=dt, args=list(df=2), colour="red", size=2) +
+   ggtitle("t-Distribution of df=2")

 

 

 

 

 

(6) 카이제곱분포 확률밀도곡선 (Chisq Distribution Probability Density Curve)
     : stat_function(fun = dchisq)

 

> # 카이제곱분포 : fun = dchisq
> ggplot(data.frame(x=c(0,10)), aes(x=x)) +
+   stat_function(fun=dchisq, args=list(df=1), colour="black", size=1.2) +
+   geom_text(x=0.6, y=1, label="df=1") +
+   
+   stat_function(fun=dchisq, args=list(df=2), colour="blue", size=1.2) +
+   geom_text(x=0, y=0.55, label="df=2") +
+   
+   stat_function(fun=dchisq, args=list(df=3), colour="red", size=1.2) +
+   geom_text(x=0.5, y=0.05, label="df=3") +
+   
+   ggtitle("Chisq-Distribution")

 

 

 

 

 

(7) 지수분포 (Exponential Distribution) : stat_function(fun = dexp)

 

> # 지수분포 : fun = dexp
> ggplot(data.frame(x=c(0,10)), aes(x=x)) +
+   stat_function(fun=dexp, colour="brown", size=1.5) +
+   ggtitle("Exponential Distribution")

 

 

 

 

 

(8) F 분포 (F Distribution) : stat_function(fun = df)

 

> # F분포 : fun = df
> ggplot(data.frame(x=c(0,5)), aes(x=x)) +
+   stat_function(fun=df, args=list(df1=5, df2=10), colour="purple", size=1) +
+   ggtitle("F Distribution of (df1=5, df2=10)")
 

 

 

 

(9) 감마 분포 (Gamma Distribution) : stat_function(fun = dgamma)

 

> # 감마 분포 : fun = dgamma
> ggplot(data.frame(x=c(0, 400)), aes(x=x)) +
+   stat_function(fun=dgamma, args=list(shape=5, rate=0.05), colour="green") +
+   ggtitle("Gamma Distribution of (shape=5, rate=0.05)")

 

 

 

 

 

 

(10) 균등분포 (Uniform Distribution) : stat_function(fun = dunif)

 

> # 균등분포 : fun = dunif
> ggplot(data.frame(x=c(-2,20)), aes(x=x)) +
+   stat_function(fun=dunif, args=list(min = 0, max = 10), colour="black", size=1) +
+   ggtitle("Uniform Distribution of (min=1, max=10)")

 

 

 

 

 

 

덤으로, 상용로그분포와 사인 함수, 코사인 함수 곡선도 그려보겠습니다.

 

(11) 상용로그분포 (Common Logarithm Distribution) : stat_function(fun = log10)

 

> # 상용로그분포 : fun = log10
> ggplot(data.frame(x=c(0,100)), aes(x=x)) +
+   stat_function(fun=log10, colour="black", size=1.5) +
+   geom_vline(xintercept=10, colour="grey", linetype="dashed", size=1) +
+   geom_vline(xintercept=100, colour="grey", linetype="dashed", size=1) +
+   ggtitle("Common Logarithm Distribution")

 

 

 

 

 

 

(12) 사인 함수 곡선(Sine Function Curve), 코사인 함수 곡선(Cosine Function Curve) :

      stat_function(fun = sin), stat_fuction(fun = cos)

 

> # 사인 함수 : fun = sin, 코사인 함수 : fun = cos
> ggplot(data.frame(x=c(0,6.28)), aes(x=x)) +
+   stat_function(fun=sin, colour="blue", size=1) +
+   geom_text(x=0.2, y=0, label="sine curve") +
+   
+   stat_function(fun=cos, colour="yellow", size=1) + 
+   geom_text(x=0.2, y=1, label="cosine curve") +
+   
+   geom_vline(xintercept=3.14, colour="grey", linetype="dashed", size=1) + # pi값에 세로 직선 추가  
+   geom_vline(xintercept=6.28, colour="grey", linetype="dashed", size=1) + # 2pi값에 세로 직선 추가  
+   ggtitle("Sine(blue curve), Cosine(yellow curve) Function")

 

 

 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,