R flextable conditional formatting based on pairs of rows

后端 未结 1 560
慢半拍i
慢半拍i 2021-01-16 19:02

I am trying to change the bg color of some cells in a flextable based on whether the values in the rows labeled Act (for actual) excee

相关标签:
1条回答
  • 2021-01-16 19:41

    I'm sure there is a more elegant way to solve this, and if there is, I hope someone posts it. But in the meantime I found a stopgap. First split the df into plan values and actual values, and then use those differences to determine appropriate color for each cell:

    library(gdata)
    
    df %>% group_split(Type) -> plan.act
    ifelse(plan.act[[1]][,3:14]-plan.act[[2]][,3:14]>=0, "#cceecc", "#eecccc") -> colorgrid 
    

    This creates a list of red/green colors for each cell:

    > colorgrid
         JAN       FEB       MAR       APR       MAY       JUN       JUL       AUG       SEP       OCT NOV DEC
    [1,] "#cceecc" "#eecccc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" NA  NA  NA 
    [2,] NA        NA        "#cceecc" NA        NA        "#cceecc" NA        NA        "#eecccc" NA  NA  NA 
    [3,] "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" "#cceecc" NA  NA  NA 
    [4,] NA        NA        "#eecccc" NA        NA        "#eecccc" NA        NA        "#eecccc" NA  NA  NA 
    [5,] NA        NA        "#cceecc" NA        NA        "#cceecc" NA        NA        "#cceecc" NA  NA  NA 
    [6,] "#eecccc" "#eecccc" "#cceecc" "#eecccc" "#eecccc" "#cceecc" "#eecccc" "#cceecc" "#cceecc" NA  NA  NA 
    [7,] NA        NA        NA        NA        NA        NA        NA        NA        NA        NA  NA  NA 
    

    Now create another df for colors for the Plan group, then plot the table:

    blankgrid <- colorgrid
    blankgrid[!is.na(blankgrid)] <- NA_character_
    
    df %>% regulartable() %>% bg(j = 3:14, bg=interleave(blankgrid,colorgrid))
    

    And from there you can add more flextable goodness to make table prettier:

    df %>% regulartable() %>% bg(j = 3:14, bg=interleave(blankgrid,colorgrid)) %>%
         merge_v(j=1) %>% border_inner_v(border = fp_border(color="gray", width=1))
    

    0 讨论(0)
提交回复
热议问题