Home > Software engineering >  How to replicate the same expression with tidyverse pipe operator in r?
How to replicate the same expression with tidyverse pipe operator in r?

Time:12-17

I would like to highlight corresponding values in each column in the data using DT::datatble.

For example:

library(tidyverse)
data(mtcars)
mtcars <- mtcars %>% mutate(across(everything(), as.character))


datatable(mtcars[, c("vs", "am")]) %>%
  formatStyle("vs", backgroundColor = styleEqual(rep(0, sum(mtcars$vs == 0)), rep("yellow", sum(mtcars$vs == 0)))) %>%
  formatStyle("am", backgroundColor = styleEqual(rep(1, sum(mtcars$am == 1)), rep("yellow", sum(mtcars$am == 1))))

In the real case, I have multiple columns and I would like to iterate all columns to add formatStyle. Is there any way to replicate the %>% formatstyle() in the loop:

# something to start
l <- list()
l[["vs"]] <- 0  
l[["am"]] <- 1

datatable(mtcars[, c("vs", "am")]) %>%
lapply(l, function(i) {
   i ... # multiple formatStyle()
})

The purpose of iteration on each column is not to highlight 1 in vs, or 0 in am.

Thank you!

CodePudding user response:

An option is to do a for loop and update

library(dplyr)
library(DT)

mtcars <- mtcars %>% 
     mutate(across(everything(), as.character))

dt1 <- datatable(mtcars %>% 
          select(vs, am))
nm1 <- list(vs = 0, am = 1)
for(i in seq_along(nm1)) {
  
  dt1 <- dt1 %>%
    formatStyle(names(nm1)[i], backgroundColor = styleEqual(rep(nm1[[i]], 
        sum(mtcars$vs == nm1[[i]])), rep("yellow", sum(mtcars$vs == nm1[[i]]))))
  
}
dt1

-output

enter image description here

  • Related