[R] Table with n(%) formatting: A better way to do this?
Duncan Murdoch
murdoch.duncan at gmail.com
Wed Apr 10 18:36:56 CEST 2013
On 10/04/2013 11:59 AM, Paul Miller wrote:
> 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
This might not be very useful for you, but the tables package can
calculate proportions and percentages directly from the data. It can
produce LaTeX output, but doesn't have formatting functions for HTML or
odf. Still, you might use it for the computing, then output .csv and
format it later. For example, you get a table something like the one
produced above from the breaks dataframe using
tabular((wool + 1) ~ (tension + 1)*((Count=1) + Percent("col")),
data=breaks)
It's possible to get the formatting closer to what you had with
fiddling, but not easy to do it in a way that looks good in all possible
output formats.
Duncan Murdoch
More information about the R-help
mailing list