Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grid.table() conditional formatting in R

Tags:

r


I was looking at this link, that produces a grid table and does text formatting. Is there any way I can do conditional formatting? For e.g.

  1. Set background color based on the value
  2. Show negative values as red and blue otherwise

source("http://gridextra.googlecode.com/svn/trunk/inst/tableGrob2.r")
library(grid)

tc  = textConnection("
 carat   VeryLongWordIndeed color clarity depth
14513  1.35 Ideal     J     VS2  61.4
28685  0.30  Good     G    VVS1  64.0
50368  0.75 Ideal     F     SI2  59.2")
d = read.table(tc,head=T)
close(tc)
grid.newpage()
g = grid.table2(d)
grid.gedit(paste("cells-fill-",1,2,sep=""), gp=gpar(fill="red"))

This works as expected. But if you have more than 10 rows, it doesn't. It colors more than one cell. For e.g.

d<-do.call("rbind", replicate(10, d, simplify = FALSE))
grid.newpage()
g = grid.table2(d)
grid.gedit(paste("cells-fill-",1,2,sep=""), gp=gpar(fill="red"))

How to avoid this?

like image 726
Neerav Avatar asked Mar 03 '26 11:03

Neerav


1 Answers

There was a way in earlier versions of grid.table; unfortunately it is not compatible with some of the later features. I have placed a copy of the code in inst/tableGrob2.r. You can try,

library(grid)

 tc  = textConnection("
     carat   VeryLongWordIndeed color clarity depth
 14513  1.35 Ideal     J     VS2  61.4
 28685  0.30  Good     G    VVS1  64.0
 50368  0.75 Ideal     F     SI2  59.2")
 d = read.table(tc,head=T)
 close(tc)
 grid.newpage()
 g = grid.table2(d)
 grid.ls(g)
 grid.gedit("top-head-fill-(1|3|5)", gp=gpar(fill="red"))
 grid.gedit("cells-fill-.3", gp=gpar(fill="green"))
 grid.edit("cells-label-33", label=expression(alpha),gp=gpar(col="orange"))
like image 85
baptiste Avatar answered Mar 05 '26 03:03

baptiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!