I have been trying to learn how to format tables for output in R. I'm now trying to take the table in example and format the numbers in the columns. I would like to have two digits in some columns and none in some columns like the rank column. Also, I would like to keep the row names as Year Month. How would one go about creating a table like this?
Note: Also the "3" in the column 'sepal.with' is printed as "3" not "3.0".
library(gtable)
library(grid)
library(gridExtra)
library(zoo)
iris <- as.matrix(iris[1:4, 1:3])
rownames(iris)<-as.yearmon(seq(as.Date("2000/1/1"), as.Date("2000/4/1"), by = "month"))
RankColumn<-seq(1, 4, by = 1)
iris<-cbind(iris, RankColumn)
iris<- round(as.matrix(iris), digits=2)
# a simple function to scale each column to the range [0, 1]
norm <- function(x) {
apply(x, 2, function(y){(y-min(y))/(max(y)-min(y))})
}
bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)
tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))
g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)