[R] Table with n(%) formatting: A better way to do this?
Paul Miller
pjmiller_57 at yahoo.com
Wed Apr 10 17:59:06 CEST 2013
Hello All,
Am learning to create tables with n(%) formatting using R. Below is a working example. I think this is not bad but wondered if there are better ways of doing it. Although it can be quite humbling, seeing good code helps me assess my progress as an R programmer.
Ultimately want to have code that I can turn into a function. Will then use the output produced to make tables using odfWeave and Sweave/knitr.
Thanks,
Paul
breaks <- as.data.frame(lapply(warpbreaks, function(x) rep(x, warpbreaks$breaks)))
Freq <- with(breaks, addmargins(table(wool, tension), 2))
Prop <- round( prop.table(Freq, 2) * 100, 2 )
Freq <- addmargins(Freq, 1)
Prop <- addmargins(Prop, 1)
require(odfWeave)
class(Freq) <- "character"
class(Prop) <- "character"
FreqProp <- matrixPaste(Freq, "(", Prop, "%)", sep = c("", "", ""))
colnames(FreqProp) <- colnames(Freq)
rownames(FreqProp) <- rownames(Freq)
names(dimnames(FreqProp)) <- c("Wool", "")
FreqProp <- data.frame(Wool=rownames(FreqProp), FreqProp, row.names=NULL, stringsAsFactors=FALSE)
names(FreqProp)[names(FreqProp) == "Sum"] <- "Total"
FreqProp$Wool[FreqProp$Wool == "Sum"] <- "Total"
FreqProp
More information about the R-help
mailing list