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 Contingency Table Data | |
a=371 # Exposed Case | |
b=62 # Non-exposed Case | |
c=85 # Exposed Control | |
d=18 # Non-exposed Control | |
tbl <- matrix(c(a, c, b, d), nrow = 2, | |
dimnames=list(Case=c("Case", "Control"), | |
Exposed=c("Exposed", "Unexposed"))) | |
tbl | |
# Function to Convert Table to Data Frame | |
tbl_df <- function(tbl) | |
{ | |
rows <- c(rep(row.names(tbl)[1],sum(tbl[1,])),rep(row.names(tbl)[2],sum(tbl[2,]))) | |
cols <- c(rep(colnames(tbl)[1],sum(tbl[1,1])),rep(colnames(tbl)[2],sum(tbl[1,2])), | |
rep(colnames(tbl)[1],sum(tbl[2,1])),rep(colnames(tbl)[2],sum(tbl[2,2]))) | |
out <- data.frame(rows,cols) | |
names(out) <- names(dimnames(tbl)) | |
return(out) | |
} | |
# Run Function and Save Output | |
out <- tbl_df(tbl) | |
# Confirm Function | |
head(out) | |
tbl2 <- table(out$Case,out$Exposed) | |
tbl2 | |
tbl2 == tbl | |
# Example Statistical Tests | |
r <- cor(as.numeric(out$Case)-1,as.numeric(out$Exposed)-1) | |
r**2 | |
chisq.test(tbl, correct=F) |
No comments:
Post a Comment