Making confidence interval function in R.

485 Views Asked by At

I want to make confidence interval function in R I'm trying to make following this one(Ration confidence interval function).

p.conf=function(x,n,alpha){
  phat=x/n
  z=qnorm(1-alpha/2)
  ss=sqrt(phat*(1-phat)/n)
  if(n*phat>=15 & n*(1-phat)>=15)
  phat+c(-z*ss,z*ss) else print ("z cannot")                                                          
}

But I can't get how to make one when I know about specimen of Population. I want to have similar form with those code I uploaded. Please help me.

1

There are 1 best solutions below

0
On

If $X_1, X_2, \dots, X_n$ is a sample of size $n$ from a normal population, then a confidence interval for the population mean $\mu$ is $\bar X \pm t^* s/\sqrt{n}.$

In R, $\bar X$ can be found as a = mean(x) where x is an $n$-vector of data, $s$ can be found as s = sd(x) and $t^*$ as t.star = qt(1 - alpha/2, n-1), where the confidence level is $1 - \alpha/2.$ For example, a 95% confidence interval would use $\alpha = .05.$ The function qt is the quantile function of Student's t distribution. I will leave it to you to combine everything into a function (perhaps using pm = c(-1,1) for $\pm$).

BTW: The binomial confidence interval you are using is not the best. The 'plus-4' or 'Agresti' confidence interval is now generally recognized as more accurate. If there are $X$ successes in $n$ trials, it is of the form $$\tilde p \pm z^*\sqrt{\tilde p(1-\tilde p)/\tilde n},$$ where $\tilde n = n + 4$ and $\tilde p = (X+2)/\tilde n.$

This formula is best for 95% confidence intervals. Even more accurate is the (more intricate) Wilson confidence interval. See Wikipedia.