Search code examples
rlatexsweave

Color Coding Sweave Only Partially Working


I am still working on this question. I've got it so it gives the correct cells red backgrounds, but it is not giving the other cells green backgrounds.

Note: I am using sweave only, not knitr.

Here is my code:

<<>>=
Flag <- data.frame(HOSP,Dept, Overall, DC_Info, Care_Trans)
@  
<<results=tex>>=
color_cells <- function(df, var){
  out <- ifelse(df[, var]=="", 
                  paste0("\\cellcolor[HTML]{2DB200}{", df[, var], "}"),
                  paste0("\\cellcolor[HTML]{FF0600}{", df[, var], "}"))
}
Flag$Overall <- color_cells(df = Flag, var= "Overall")
Flag$DC_Info <- color_cells(df = Flag, var= "DC_Info")
Flag$Care_Trans <- color_cells(df = Flag, var= "Care_Trans")
@

<<results=tex>>=
Flagx <- xtable(Flag)
align(Flagx) <- "|c|l|l|c|c|c|"
print(Flagx[1:40,], hline.after=c(-1:40), sanitize.text.function=identity,
sanitize.colnames.function = Hmisc::latexTranslate)
@

Solution

  • A couple of things that may be contributing:

    This is subtle and I've missed it even in the earlier questions. In your color_cells function, you are assigning a character string to out, but you aren't returning the value of out. You should write your function in one of the two following ways:

    color_cells <- function(df, var){
      ifelse(df[, var]=="", 
             paste0("\\cellcolor[HTML]{2DB200}{", df[, var], "}"),
             paste0("\\cellcolor[HTML]{FF0600}{", df[, var], "}"))
    }
    

    OR

    color_cells <- function(df, var){
      out <- ifelse(df[, var]=="", 
                    paste0("\\cellcolor[HTML]{2DB200}{", df[, var], "}"),
                    paste0("\\cellcolor[HTML]{FF0600}{", df[, var], "}"))
      out
    }
    

    Another issue that may be contributing (though I'm not entirely sure in this case) is whether your columns have any NA values. Watch what happens if a value is NA: The logical comparison doesn't resolve and returns NA without applying any color.

    > ifelse(NA == "", "red", "green")
    [1] NA
    

    You can modify your cell_colors function to handle theNA`'s with something like

    color_cells <- function(df, var){
     df[, var][is.na(df[, var])] <- ""
     ifelse(df[, var]=="", 
            paste0("\\cellcolor[HTML]{2DB200}{", df[, var], "}"),
            paste0("\\cellcolor[HTML]{FF0600}{", df[, var], "}"))
    }