Home > Bayes rule > Bayes Rule in R

Bayes Rule in R

On Friday, I gave several examples of Bayes’ rule in class. I’ll do a slight generalization of the testing for a disease example to illustrate using a special R function bayes to do the calculations.

This special function can be read into R directly from my web site.

> source("http://personal.bgsu.edu/~albert/MATH6480/R/bayes.R")

This function has three inputs prior, likelihood, and data.

1. The prior. Here there are two models — either we have the disease (D) or we don’t (not D) — and suppose that the probability of D is only 0.0001. prior is a vector of probabilities, where we give names to the two values:

> prior = c(D = .0001, not.D = 1 - .0001)

2. The likelihood. Here the data is the test result (pos or neg) where the test result is incorrect with probability 0.01. We’ll specify the likelihood as a matrix where each row of the matrix gives the probability of pos and neg for each model.

> like.D = c(pos=.99, neg=.01)
> like.not.D = c(pos=.01, neg=.99)
> likelihood = rbind(D = like.D, not.D = like.not.D)
> likelihood
pos neg
D 0.99 0.01
not.D 0.01 0.99

3. data is a vector of data values. Suppose we get a positive test result (pos). Then

> data="pos"

So we enter as inputs prior, likelhood, and data — the output is a matrix — the first row gives the prior probs and the second row gives the posterior probabilities.

> bayes(prior, likelihood, data)

D not.D
prior 0.000100000 0.9999000
pos 0.009803922 0.9901961

Although the positive blood test result is “bad news”, it is still very unlikely that you have the disease.

Categories: Bayes rule
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: