In this script you manually enter your data (as you would see it in a 2x2 table) and then calculate the estimated frequency and 95% CI around that frequency using the binom.confint function in the binom package. Next, a parametric and non-parametric p-value is calculated with the binom.test and fisher.test commands, respectively. These statistics are then plotted using the R's barplot function. The example code is below along with what the plot will look like. P-values and N's are automatically filled and the y limits are calculated to ensure the graph includes all the plotted details.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Input Data | |
a=35 # Exposed Cases | |
b=500 # Unexposed Cases | |
c=10 # Exposed Controls | |
d=490 # Unexposed Controls | |
# Make 2x2 Table | |
data= | |
matrix(c(a, c, b, d), | |
nrow = 2, | |
dimnames = list(Case=c("Yes", "No"), | |
Exposed=c("Yes", "No"))) | |
data | |
# Calculate 95% CI around estimate | |
library(binom) | |
cases <- binom.confint(a,a+b, methods=c("asymptotic")) | |
controls <- binom.confint(c,c+d, methods=c("asymptotic")) | |
estimates <- as.data.frame(rbind(cases,controls)) | |
# Conduct association tests | |
f=fisher.test(data) | |
c=chisq.test(data) | |
# Make barplot | |
b=barplot(estimates$mean, main="Differences in Frequency", | |
xlab="", names.arg=c(paste("Cases (N=",estimates$n[1],")",sep=""),paste("Controls (N=",estimates$n[2],")",sep="")), | |
ylab="Frequency", ylim=c(0,max(estimates$upper)*1.05), | |
border=c("white","white")) | |
arrows(x0=b,y0=estimates$lower,x1=b,y1=estimates$upper, angle=90, code=3) | |
mtext(paste("Pearson p-value=",round(c$p.value,4)),3, line=-2) | |
mtext(paste("Fisher p-value=",round(f$p.value,4)),3, line=-3) | |
box() |
No comments:
Post a Comment