Confidence interval for a proportion when sample proportion is almost 1 or 0 I know there are methods to calculate a confidence interval for a proportion to keep the limits within (0, 1), however a quick Google search lead me only to the standard calculation: $\hat{p} \pm 1.96*\sqrt\frac{\hat{p}(1-\hat{p})}{N}$.  I also believe there is a way to calculate the exact confidence interval using the binomial distribution (example R code would be nice).  I know I can use the prop.test function to get the interval but I'm interested in working through the calculation.
Sample situations (N = number of trials, x = number of success):
N=40, x=40
N=40, x=39
N=20, x=0
N=20, x=1

 A: Use a Clopper-Pearson interval?
Wikipedia discribes how to do this here:
http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval 
For example if you take your 39 successes in 40 trial example you get:
> qbeta(.025,39,2) #qbeta(alpha/2,x,n-x+1) x=num of successes and n=num of trials
[1] 0.8684141
> qbeta(1-.025,39,2)
[1] 0.9938864

For your 40 out of 40 you get:
> qbeta(1-.025,40,1)    
[1] 0.9993673
> qbeta(.025,40,1)
[1] 0.9119027

A: Why not just do this in a Bayesian way?
That is, set up a beta-distributed prior, and choose some interval whose integral is as big as you want it (working out from the mode, for example).
A: Clopper-Pearson is an exact binomial method and can be used to get confidence intervals for p even when the number of successes is 0 out of N or N out of N.  in the first case it will give an interval from 0 to A where A depends on N and alpha and from B to 1 in the latter case.
A: There are many confidence intervals for single proportions and most of them have poor performance for $p$ close to 0 or 1. The "exact" Clopper-Pearson interval mentioned above is very conservative in that setting, meaning that the actual coverage of the interval can be quite a bit larger than the nominal $1-\alpha$.
An interval that has pretty good performance for $p$ close to 0 or 1 is actually the Bayesian credible interval using the Jeffreys prior. See e.g. this paper by Brown, Cai and DasGupta (2002). It is simple to compute in R:
qbeta(c(alpha/2,1-alpha/2),x+0.5,n-x+0.5)

Nevermind that it is Bayesian by nature - it has been shown over and over again to have good frequentist performance!
(Although the Bayesian Jeffreys interval usually is recommended in this setting, it is possible to construct intervals that simultaneously give higher confidence and lower expected length for small $p$; see a recent manuscript of mine.)
