# How to calculate confidence interval for count data in R?

As question, I have found something similar here, but how to do it in R?

• Is the example at stats.stackexchange.com/q/5206/919 helpful?
– whuber
Commented May 18, 2011 at 5:06
• poisson.test gives identical answers to the page that you pointed to for count data. Commented Dec 23, 2011 at 13:44

You are looking for a confidence interval around the count from a Poisson process. If you put for example 42 into your linked example you get

You observed 42 objects in a certain volume or 42 events in a certain time period.

Exact Poisson confidence interval:

• The 90% confidence interval extends from 31.94 to 54.32
• The 95% confidence interval extends from 30.27 to 56.77
• The 99% confidence interval extends from 27.18 to 61.76

You can get this in R using poisson.test. For example

> poisson.test(42, conf.level = 0.9 )

Exact Poisson test

data:  42 time base: 1
number of events = 42, time base = 1, p-value < 2.2e-16
alternative hypothesis: true event rate is not equal to 1
90 percent confidence interval:
31.93813 54.32395
sample estimates:
event rate
42


and similarly the other values by changing conf.level. If you do not want all the background information, try something like

> poisson.test(42, conf.level = 0.95 )\$conf.int
[1] 30.26991 56.77180
attr(,"conf.level")
[1] 0.95


If the number of event is too small, it would be better to use the exact method.

exactPoiCI <- function (X, conf.level=0.95) {
alpha = 1 - conf.level
upper <- 0.5 * qchisq((1-(alpha/2)), (2*X))
lower <- 0.5 * qchisq(alpha/2, (2*X +2))
return(c(lower, upper))
}
exactPoiCI(42, 0.9)
exactPoiCI(42)
exactPoiCI(42, 0.99)


Reference: Liddell FD. Simple exact analysis of the standardised mortality ratio. J Epidemiol Community Health. 1984;38:85-8 (link)

• Welcome to the site. Do you mind expanding upon this. What exactly does "count data is too small" mean (sample size small or intensity of events is too small?) A reference would be appreciated as well. Commented Dec 23, 2011 at 13:09

The first answer using poisson.test does give the exact confidence interval. However, this calculation is so simple that I prefer to calculate it directly instead of using a library function. In the second answer, there is a minor error. The +2 should be in the degree of freedom for the upper CI calculation, not for the lower one. So the correct code should be:

exactPoiCI <- function (X, conf.level=0.95) {
alpha = 1 - conf.level
upper <- 0.5 * qchisq(1-alpha/2, 2*X+2)
lower <- 0.5 * qchisq(alpha/2, 2*X)
return(c(lower, upper))
}

exactPoiCI(42, 0.9)
exactPoiCI(42)
exactPoiCI(42, 0.99)

• But this is already present in the other answer. Why did you put this here? Commented Nov 19, 2015 at 11:34
• The other answer had an error, this is a correction. Note the +2 is in the upper CI calculation. Commented Nov 19, 2015 at 11:36
• Welcome to the site and thank you for correcting the error. Commented Nov 19, 2015 at 11:57