How to replace 0's with blank in kables
I'm creating a rather large html table using the kable function, and this table has a lot of 0's in it. In order to only show the relevant information more clearly, I'm trying hide the 0's in the table by just replacing them with blank space.
Right now, I'm trying something like this but it's not working:
my_table = knitr::kable(...) cat(gsub(0," ",my_table), sep = '\n')
Something similar to the above works to remove NA's, but I can't seem to get it to work for 0's.
Thanks in advance!
EDIT: example data:
Product = c('A','B','A','A','C','B') Month = c('Jan', 'Feb', 'Feb', 'Apr', 'Jan', 'Feb') my_data = data.frame(Product, Month) my_table = table(my_data) kable(my_table) #This has the 0's which I don't want Product | Month A | Jan B | Feb A | Feb A | Apr C | Jan B | Feb
----Jan Feb Mar Apr A 1 1 0 1 B 0 2 0 0 C 1 0 0 0
----Jan Feb Mar Apr A 1 1 - 1 B - 2 - - C 1 - - -
except "-" would be a blank space instead of a dash
EDIT2: never mind, I figured it out even though this is really hacky:
my_kable = knitr::kable(my_table) gsub(0, ' ', my_kable)
The reason your original
gsubwasn't working was that it was flattening the table to a vector. One of many options to maintain the table structure would be to use the
knitr::kable(replace(my_table, my_table==0, "")) #| |Apr |Feb |Jan | #|:--|:---|:---|:---| #|A |1 |1 |1 | #|B | |2 | | #|C | | |1 |
You can use base
gsub(0, " ", kable(my_table))
| | Apr| Feb| Jan| |:--|---:|---:|---:| |A | 1| 1| 1| |B | | 2| | |C | | | 1|