I am creating some contingency tables/crosstabs in R that I want to move to Excel for use in a Word document. I've found discussions on how to write to excel in a few questions- How to export multivariate forecast results from R to excel Export data from R to excel. But contingency tables' formats (either using base R or packages like descr or gmodels) don't seem to translate well to Excel.
I've come up with my own solution, which produces what I want, but I wonder if there's a more efficient way, e.g. a package I'm overlooking.
library(xlsx)
test.data <- as.data.frame(matrix(sample.int(2,size = 10*2, TRUE), nrow = 10, ncol = 2))
out1 <- table(test.data$V1, test.data$V2)
out.p <- prop.table(out1,2)
out.d <- as.data.frame.matrix(out1)
out.pd <- round(as.data.frame.matrix(out.p),2)
colnames(out.d) <- c("No", "Yes")
colnames(out.pd) <- c("No", "Yes")
out.d1 <- paste(out.d$No, " (",out.pd$No,")",sep="")
out.d2 <- paste(out.d$Yes," (",out.pd$Yes,")", sep="")
out2 <- cbind(out.d1,out.d2)
toadd.r <- c("No","Yes")
out2 <- cbind(toadd.r,out2)
sig <- unlist(summary(table(test.data$V1,test.data$V2)))
sig <- rep(round(sig[6],2),nrow(out2))
out2 <- cbind(out2, sig)
colnames(out2) <- c("Outcome","No","Yes","sig")
write.xlsx(out2, file ="Output.xlsx", sheetName = "Test1")