dbosak01 / sassy

A meta-package for providing SAS®-like functionality to R.
Creative Commons Zero v1.0 Universal
21 stars 4 forks source link

Add coloring table cells by value #43

Closed tarlgordon closed 7 months ago

tarlgordon commented 11 months ago

It would be awesome to be able to color cells in a table by value. For example, specifying one column that 0% is dark red, 0-50% is bright red, 50-80% is orange, 80-90% is yellow and 90%+ is green. Another may be more arbitrary, 0-5 red, 5-10 yellow, 10-15 green.

I have been kludging together html reports for coming up on 10 years using ggplot2 and xtable and coming up with clever regular expressions to color cells and I'm excited that this may be a far more easily maintained, far more modular and far quicker to develop methodology.

dbosak01 commented 11 months ago

I can do this in HTML. In RTF, I can control bolding by cell. I've got all this cell styling in the queue. I've wanted to do it for a long time. Let me send you an example with HTML. Not sure when the other report formats will be accomplished. Every format is different, so they all have to be done independently. PDF is particularly difficult. Thanks for your comment. It helps me to know what people are looking for.

dbosak01 commented 11 months ago

Somehow I thought I could do this in HTML. But now that I investigate, I think it was just something I was planning but never implemented. Sorry about that. I will up the priority on this feature. The best I can do currently is conditional bolding:

library(reporter)

# Create temporary path
tmp <- file.path(tempdir(), "example12k.rtf")

# Prepare data
df <- data.frame(names = rownames(mtcars), mtcars[, 1:3])

# Set style indicator variable
df$mpgind <- ifelse(df$mpg > 20, TRUE, FALSE)

# Create table
tbl <- create_table(df, first_row_blank = TRUE, 
                    header_bold = TRUE, borders = c("top", "bottom")) %>% 
  define(names, label = "Car Name") %>%
  define(mpg, label = "Miles Per Gallon", 
         style = cell_style(bold = TRUE, indicator = "mpgind")) %>% 
  define(cyl, label = "Cylinders") %>% 
  define(disp, label = "Displacement")  %>% 
  define(mpgind, visible = FALSE) %>%
  titles("Table 1.0", "MTCARS with Indicator Variable", 
         borders = "none", bold = TRUE, font_size = 11) %>% 
  footnotes("* Motor Trend, 1974", borders = "none", blank_row = "none")

# Create report and add custom style
rpt <- create_report(tmp, output_type = "RTF", font = "Arial") %>% 
  add_content(tbl) 

# Write out report
write_report(rpt)

# View report
# file.show(tmp)
tarlgordon commented 11 months ago

Thank you for thinking about it and considering it in the future.

For the record, the package flextable does have formatting for data frames. I don't know if that would end up being a straightforward data type to implement or a path you'd be interested in going in.

dbosak01 commented 7 months ago

Moved this to reporter package #326