Nice Tables from R Data Frames
The knitr package provides the kable function, which allows you to export data frames as HTML, markdown, and more. It’s really useful along with some background with LaTeX or HTML/CSS to make nicely formatted tables directly from your R output. The code below should get you started.
(Bonus: a brief look at plyr power!)
#install.packages('knitr')
require(knitr)
#lets use the apropos Number of Breaks in Yarn during Weaving data
data(warpbreaks)
#check it out
summary(warpbreaks)
#Let's get the mean and SD for each level of wool
# at each level of tension.
#install.packages('plyr') # This is a great package
require(plyr)
#Split the data by wool and tension, get mean and sd for each
# and return a data frame.
descriptives<-ddply(.data=warpbreaks,
.variables=c('wool','tension'),
.fun=function(x){
round(c(Mean=mean(x$breaks),SD=sd(x$breaks)),2)
})
descriptives
#The default is markdown, and looks pretty good to copy and
# past into a text file.
kable(descriptives)
myHTMLTable<-kable(descriptives,format='html',output=F) getwd() #what directory will it save into? write(myHTMLTable,file='table.html') #Check out the html, and buff it up if you want! #Further reading: # ?kable # ?plyr # Also, google 'markdown' and 'pandoc'
This is the html output:
wool | tension | Mean | SD |
---|---|---|---|
A | L | 44.56 | 18.10 |
A | M | 24.00 | 8.66 |
A | H | 24.56 | 10.27 |
B | L | 28.22 | 9.86 |
B | M | 28.78 | 9.43 |
B | H | 18.78 | 4.89 |
A quick follow-up: If you’re looking to show your table to someone else quickly, and want to make the table look nice, open the table.html file that contains the output from
kable
. Thekable
command above creates just the HTML for the table itself. Thus, we can add a few lines of code to the top of the file in order to change how the table looks:<style>
/* CSS Style instructions go here. */
</style>
[table code from kable is here]
CSS (“Cascading Style Sheets”) is the language used to change how things look in HTML. Do a quick web search for “Table CSS Examples” and you’ll find plenty of quick examples for styling the table. For example, taking the code from http://veerle-v2.duoh.com/blog/comments/a_css_styled_table_version_2/ , we would add the following to the top of the table.html:
<style>
table {
width:90%;
border-top:1px solid #e5eff8;
border-right:1px solid #e5eff8;
margin:1em auto;
border-collapse:collapse;
}
td {
color:#678197;
border-bottom:1px solid #e5eff8;
border-left:1px solid #e5eff8;
padding:.3em 1em;
text-align:center;
}
</style>