Steve Kaszycki - 1 month ago 5

R Question

I have a matrix of data, which I will display in a Shiny app in tableOutput format. And I have a vector of colornames determined exogenous to the code. I need to set the background of column[i] to color[i].

For instance, if I have the following:

`helpme <- data.frame(matrix(rnorm(200),nrow=20))`

helpme.colors <- c(rep("white",6),

"chocolate4",

"darkblue",

rep("black",2))

Then, what I am looking to do is something that'd function like this (R'ish pseudocode):

`for(i in 1:dim(helpme)[2]){`

BackgroundColor(helpme[,i]) <- helpme.colors[i]

}

I imagine the answer is a fairly straighforward javascript loop but I haven't been able to find it yet (I have minimal experience in javascript).

Answer

You can use some r package

1) `DT`

```
library(DT)
ddd=datatable(helpme)
for (i in 1:ncol(helpme)){
ddd=ddd%>%formatStyle(i,backgroundColor=helpme.colors[i])
}
ddd
```

2) `htmlTable`

```
htmlTable::htmlTable(helpme,css.cell=sapply(1:ncol(helpme),function(i) paste0("background-color:",helpme.colors[i],"")))
```

*PS there is problem with "chocolate4"*

Source (Stackoverflow)

Comments