writing from r to excel (6*1) <-one or (0.5*12) <-other

Willie knows...

Willie knows…

Many clients or coworkers will prefer you provide any analytic output in excel (vs. fixed-width or *.csv), and so it is wise to have a bag of tricks that includes the ability to output work product in Excel. One powerful side-effect of doing so is that you can output multiple tables as separate tabs within the same worksheet. That is what the example code chunk below allows you to do. The chunk below leans heavily upon the work of others that I came across over the years. It requires the use of the xlsx package.

To give credit where it is rightfully due, look to the following:

Rob Kabakof wrote a helpful post about this here:http://statmethods.wordpress.com/2014/06/19/quickly-export-multiple-r-objects-to-an-excel-workbook/

There’s also an impressive implementation (which pulls in visualizations here):http://tradeblotter.wordpress.com/2013/05/02/writing-from-r-to-excel-with-xlsx/

My example chunk follows:

save.xlsx <- function (file, sheetnames, …)
{
require(xlsx, quietly = TRUE)
objects <- list(…)
objnames <- sheetnames
nobjects <- length(objects)
for (i in 1:nobjects) {
if (i == 1)
write.xlsx(objects[[i]], file, sheetName = sheetnames[i], row.names=FALSE)
else write.xlsx(objects[[i]], file, sheetName = sheetnames[i],
append = TRUE, row.names=FALSE)
}
print(paste('Workbook', file, 'has', nobjects, 'worksheets.'))
}
 
save.xlsx('myworkbook.xlsx', c('Tab1', 'Tab2', 'Tab3', 'Tab4') ,mtcars, Titanic, AirPassengers, state.x77)

Advertisements