#S+ functions for proportions to complement prop.test

# computes RD, RR , log(RR), OR, and log(OR) for indep proportions p1 and p2
# also computes approx two-sided alpha-level confidence intervals
# input arguments are counts: p1=a/(a+c), p2=b/(b+d)
# output is rounded to dig places
# use prop.test for p-value

prop.est<-function(a,b,c,d,alpha=.05,dig=3)
{
z<-qnorm(1-alpha/2)
n1<-a+c
n2<-b+d
p1<-a/n1
p2<-b/n2
rd<-p1-p2
rr<-p1/p2
or<-(a*d)/(b*c)
lrr<-log(rr)
lor<-log(or)
se.rd<-sqrt(p1*(1-p1)/n1+p2*(1-p2)/n2)
se.lrr<-sqrt(1/a-1/n1+1/b-1/n2)
se.lor<-sqrt(1/a+1/b+1/c+1/d)
rd.lcl<-rd-z*se.rd
rd.ucl<-rd+z*se.rd
lrr.lcl<-lrr-z*se.lrr
lrr.ucl<-lrr+z*se.lrr
lor.lcl<-lor-z*se.lor
lor.ucl<-lor+z*se.lor
rr.lcl<-exp(lrr.lcl)
rr.ucl<-exp(lrr.ucl)
or.lcl<-exp(lor.lcl)
or.ucl<-exp(lor.ucl)
p.out<-round(cbind(p1,p2),dig)
est<-rd
lcl<-rd.lcl
ucl<-rd.ucl
rd.out<-round(cbind(est,lcl,ucl),dig)
est<-rr
lcl<-rr.lcl
ucl<-rr.ucl
rr.out<-round(cbind(est,lcl,ucl),dig)
est<-lrr
lcl<-lrr.lcl
ucl<-lrr.ucl
lrr.out<-round(cbind(est,lcl,ucl),dig)
est<-or
lcl<-or.lcl
ucl<-or.ucl
or.out<-round(cbind(est,lcl,ucl),dig)
est<-lor
lcl<-lor.lcl
ucl<-lor.ucl
lor.out<-round(cbind(est,lcl,ucl),dig)
list(proportions=p.out,risk.difference=rd.out,risk.ratio=rr.out,
log.risk.ratio=lrr.out,odds.ratio=or.out,log.odds.ratio=lor.out)
}

#compares two indep proportions p1=x1/n1 and p2=x2/n2

prop.est2<-function(x1,n1,x2,n2){
prop.est(x1,x2,n1-x1,n2-x2)}