rhtml-tableformattable

Formattable R package: conditionaly formatting the cells' content on the basis of a numeric threshold


I have a dataframe like the following

mydata <- structure(list(Wife = c(15.972, 12.715, 8.333, 6.276, 2.179, 
-1.408, -1.649, -4.647, -7.039, -5.299, -7.411, -9.776, -9.612
), Alternating = c(-2.622, -0.548, -1.331, 3.9, -1.802, 2.08, 
1.481, 9.53, 7.709, -0.953, -4.823, -4.878, -5.245), Husband = c(-7.012, 
-5.823, -3.99, -3.324, -5.828, -4.869, -3.941, 0.515, 9.551, 
-0.868, 4.843, 24.544, -5.812), Jointly = c(-8.283, -7.569, -4.048, 
-6.564, 4.418, 4.284, 4.157, -3.006, -7.306, 7.066, 7.086, -8.306, 
19.397)), row.names = c("Laundry", "Main_meal", "Dinner", "Breakfeast", 
"Tidying", "Dishes", "Shopping", "Official", "Driving", "Finances", 
"Insurance", "Repairs", "Holidays"), class = "data.frame")

which lists the chi-square adjusted standardized residuals. Using the 'formattable' R package, I managed to get the below table (more nicely formatted than in the R console):

enter image description here

Issue

I cannot find a viable option to conditionally formatting some cells according to the size of the residual. What I am after is (for example) to have in GREEN the cells whose residual is larger than +1.96, and in RED those whose residual is smaller than -1.96. I have indeed consulted the package's vignette, with no avail.


Solution

  • library(formattable)
    library(dplyr)
    
    mydata <- structure(list(Wife = c(
      15.972, 12.715, 8.333, 6.276, 2.179,
      -1.408, -1.649, -4.647, -7.039, -5.299, -7.411, -9.776, -9.612
    ), Alternating = c(
      -2.622, -0.548, -1.331, 3.9, -1.802, 2.08,
      1.481, 9.53, 7.709, -0.953, -4.823, -4.878, -5.245
    ), Husband = c(
      -7.012,
      -5.823, -3.99, -3.324, -5.828, -4.869, -3.941, 0.515, 9.551,
      -0.868, 4.843, 24.544, -5.812
    ), Jointly = c(
      -8.283, -7.569, -4.048,
      -6.564, 4.418, 4.284, 4.157, -3.006, -7.306, 7.066, 7.086, -8.306,
      19.397
    )), row.names = c(
      "Laundry", "Main_meal", "Dinner", "Breakfeast",
      "Tidying", "Dishes", "Shopping", "Official", "Driving", "Finances",
      "Insurance", "Repairs", "Holidays"
    ), class = "data.frame")
    
    
    
    style_ci <- function(x) {
      case_when(x > 1.96 ~ "green", x < -1.96 ~ "red", TRUE ~ "black")
    }
    
    formattable(mydata, list(
      Wife = formatter("span", style = ~ style(color = style_ci(Wife))),
      Alternating = formatter("span", style = ~ style(color = style_ci(Alternating))),
      Husband = formatter("span", style = ~ style(color = style_ci(Husband))),
      Jointly = formatter("span", style = ~ style(color = style_ci(Jointly)))
    ))
    

    enter image description here