Write a loop of formatStyle in R shiny

2019-08-23 08:36发布

问题:

Guys.

I met a problem that:

I am developing a R shiny app and I want to highlight some values in the datatable.

I have a dataframe(entities) and a vector(vec1), and I want to highlight a specific value in each column when the value in each column is equal to the value in a vec1.

Now I achieved it by repeating the formatStyle code 25 times, but I believe it can be done by writing a loop. Could anyone help me?

vec1 = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)

       datatable(data = datasetInput3(), options = list(pageLength = 25)) %>% formatStyle(
      colnames(entities)[1],
      backgroundColor = styleEqual(vec1[1], c('yellow'))) %>% formatStyle(
       colnames(entities)[2],
       backgroundColor = styleEqual(vec1[2], c('yellow')))
...
%>% formatStyle(
       colnames(entities)[25],
       backgroundColor = styleEqual(vec1[25], c('yellow')))
    })

回答1:

You can do:

DT <- datatable(data = datasetInput3(), options = list(pageLength = 25))
for(i in 1:25){
    DT <- DT %>% 
            formatStyle(colnames(entities)[i], 
                        backgroundColor = styleEqual(vec1[i], c('yellow')))
}
DT