Thursday, February 12, 2015

R15. Beta Distribution in R

The Beta distribution depends on two parameters, alpha and beta. The probability is nonzero between x = 0 and x = 1, and goes to zero near the two boundaries. You can see both y[1] and y[N] are zero.


Here, x is a numeric vector from 0 to 1, with a total number of points N.


All probability density functions start with d: dnorm, dbinom, dbeta, etc. You can get a full listing by typing ?distributions at the console.


We also compare two strings. In R, comparisons are case insensitive.

# ex15.R
N <- 10000
x <- seq(0, 1, length = N)
alpha <- 2
beta <- 5
y <- dbeta(x,alpha,beta)
main <- paste("alpha =", alpha, ", beta =", beta)
plot(x, y, col='blue', type = 'l',
     ylab = 'Beta', main = main)
cat('Total Probability:  ',1/N*sum(y),'\n')
cat('Error, Total Probability:  ',1-1/N*sum(y),'\n')
m1 <- 1/N*sum(x*y)
m2 <- alpha/(alpha+beta)
cat('Approx. Mean:', m1, '\n')
cat('Mean:', m2, '\n')
error <- (m1-m2)/m2
cat('Error, Mean:   ', error, '\n')
cat('python > R:  ', 'python' > 'R')
# Total Probability:   0.9999 
# Error, Total Probability:   0.000100025 
# Approx. Mean: 0.2856857 
# Mean: 0.2857143 
# Error, Mean:    -1e-04
# python > R:   FALSE

Ouptpu:

No comments:

Post a Comment