Home > Back-end >  Create new columns conditionally in reactable from R
Create new columns conditionally in reactable from R

Time:10-11

I am trying to make a reactable with the following (I succeeded making the first but not 2 and 3):

  1. If a row in any column is above 5 or below 0.1, color that cell red.
  2. Create a new column that counts the number of red cells for every row. For instance, since the first row has two red cells, the value is 2.
  3. Create another column that is either 1 or 0: 1 if all four columns in a certain row are all white and 0 otherwise. For instance, since the 7th row does not have any red cells, the value will be 1. enter image description here
library(tidyverse)
library(reactable)

reactable(
iris,
columns = set_names(x = colnames(iris)) %>% 
    map(~ {
    colDef(
        style = function(value) {
        ds_color <- ifelse(value > 5 | value <= 0.2, "red", "white")
        list(background = ds_color)
        }
    )
    })
)

CodePudding user response:

We may use if_all/if_any

library(dplyr)
iris %>%
   mutate(color_ind = case_when(if_any(where(is.numeric), ~ 
     .x > 5|.x < 1)~ "red",TRUE ~  "white"),
   cnt_col = rowSums(across(Sepal.Length:Petal.Width, 
       ~ .x > 5|.x < 1), na.rm = TRUE),
    binary_white =  (!cnt_col))
  • Related