I encourage all my students to use R and htmlTable to generate the final tables and figures for their publications. Below find some simple code to introduce you to htmlTable. More help can be found at: https://cran.r-project.org/web/packages/htmlTable/index.html See especially the “Vignettes”.
Here’s an example of how to create a simple table using htmlTable:
First, create a simple table:
# install.packages("htmlTable") # Only need to do once
library(htmlTable)
mytable = data.frame(matrix(rep(c(2,2.58495),times=5),nrow=2,ncol=5))
names(mytable) = c("Jan","Feb","Mar","Apr","May")
rownames(mytable) = c("Rainfall (mm)","Runoff (cms)")
print(mytable)
## Jan Feb Mar Apr May
## Rainfall (mm) 2.00000 2.00000 2.00000 2.00000 2.00000
## Runoff (cms) 2.58495 2.58495 2.58495 2.58495 2.58495
This is ok but isn’t in a publishable format. Now, print it to an htmlTable:
mytableout = htmlTable (mytable)
print(mytableout,type="html",useViewer=TRUE)
Jan | Feb | Mar | Apr | May | |
---|---|---|---|---|---|
Rainfall (mm) | 2 | 2 | 2 | 2 | 2 |
Runoff (cms) | 2.58495 | 2.58495 | 2.58495 | 2.58495 | 2.58495 |
To save this to a file, use the following in R:
outdir.tables = "F:/Rdata_example/" # Any directory
setwd(outdir.tables)
sink("mytable.html")
print(mytableout,type="html",useViewer=TRUE)
sink()
Sometimes you want a specific number of significant digits.
mytable.txt = data.frame(apply(mytable,2,function(x) as.character(format(x,digits=2))))
rownames(mytable.txt) = c("Rainfall (mm)","Runoff (cms)")
mytableout = htmlTable (mytable.txt,type="html",useViewer=TRUE)
print(mytableout)
Jan | Feb | Mar | Apr | May | |
---|---|---|---|---|---|
Rainfall (mm) | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 |
Runoff (cms) | 2.6 | 2.6 | 2.6 | 2.6 | 2.6 |
To convert the html into a pdf, open the html in a web browser and print to pdf.
To add a spanner to the top:
mytableout = htmlTable (
mytable.txt,
cgroup = c("Winter","Spring"),
n.cgroup = c(2,3)
)
print(mytableout)
Winter | Spring | |||||
---|---|---|---|---|---|---|
Jan | Feb | Mar | Apr | May | ||
Rainfall (mm) | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 | |
Runoff (cms) | 2.6 | 2.6 | 2.6 | 2.6 | 2.6 |
Now, add a caption:
mytableout = htmlTable (
mytable.txt,
cgroup = c("Winter","Spring"),
n.cgroup = c(2,3),
caption = "Table 1. Mean monthly rainfall and runoff for a very boring location."
)
print(mytableout)
Table 1. Mean monthly rainfall and runoff for a very boring location. | ||||||
Winter | Spring | |||||
---|---|---|---|---|---|---|
Jan | Feb | Mar | Apr | May | ||
Rainfall (mm) | 2.0 | 2.0 | 2.0 | 2.0 | 2.0 | |
Runoff (cms) | 2.6 | 2.6 | 2.6 | 2.6 | 2.6 |