Summary Function that is compatible with xtable
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
If you like to make nice looking documents using Latex, I highly recommend using the ‘xtable‘ package. In most instances, it works quite well for producing a reasonable looking table from an R object. I however recently wanted a LaTeX table from the ‘summary’ function in base R. So naturally I tried:
library(xtable) set.seed(123) foo = rnorm(10) summary(foo) xtable(summary(foo))
Which gave me the following error:
Error in xtable.table(summary(foo)) :
xtable.table is not implemented for tables of > 2 dimensions
So I decided to create a simple function that would return a dataframe which is easy to use with xtable. Here is what I came up with.
summaryfunction= function (x){ if( is.numeric(x)!=TRUE) {stop("Supplied X is not numeric")} mysummary = data.frame( "Min." =as.numeric( min(x)), "1st Qu." = quantile(x)[2], "Median" = median(x), "Mean" = mean(x), "3rd Qu." = quantile(x)[4], "Max." = max(x), row.names="" ) names(mysummary) = c("Min.","1st Qu.","Median","Mean","3rd Qu.","Max.") return( mysummary ) }
Now, when I try to use xtable I get the following output:
% latex table generated in R 3.1.1 by xtable 1.7-4 package % Tue Nov 04 21:58:07 2014 begin{table}[ht] centering begin{tabular}{rrrrrrr} hline & Min. & 1st Qu. & Median & Mean & 3rd Qu. & Max. \ hline & -1.27 & -0.53 & -0.08 & 0.07 & 0.38 & 1.72 \ hline end{tabular} end{table}
This should lead to an easier way to incorporate more summaries when you are writing your paper, using R and Knitr of course. If you do use knitr, make sure to try the results = ‘asis’ option with xtable from R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.