Wojciech Bednarz
Wojciech Bednarz

Reputation: 19

R Formattable package - Changing Colors by Row Value in Column Containing Character Vector

I have this data.frame and I would like to use formattable package to assign a different color to each name, whereby "Bob" = "Blue", "Ashley" = "Red" etc. Any ideas?

I am just starting with r programming, but I am particularly struggling with formattable package as there are very few examples, and documentation is focused on numeric values.

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(48, 47, 40, 28, 29, 29, 27, 27, 31, 30),
  test1_score = c(18.9, 19.5, 19.6, 12.9, 11.1, 7.3, 4.3, 3.9, 2.5, 1.6),
  test2_score = c(9.1, 9.1, 9.2, 11.1, 13.9, 14.5, 19.2, 19.3, 19.1, 18.8),
  stringsAsFactors = FALSE)

I got thus far, with one value, but strugling with the rest:

  name = formatter("span", style = x ~ ifelse(x == "Bob", 
        style("background-color" = "blue", display = "block", "border-radius" = "4px", font.weight = "bold"), NA))))

how do I add other arguments from that column just like you can do with formatStyle in DT package.

%>%
  formatStyle(
    'name',
    backgroundColor = styleEqual(c('Bob', 'Ashley'), c('blue', 'red'))

Upvotes: 0

Views: 3960

Answers (1)

jburkhardt
jburkhardt

Reputation: 675

You can style the full row instead of a single cell by using the argument target = 'row' in formatStyle().

Here is the .Rmd code chunk:

```{r data}
library(formattable)
library(DT)
df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(48, 47, 40, 28, 29, 29, 27, 27, 31, 30),
  test1_score = c(18.9, 19.5, 19.6, 12.9, 11.1, 7.3, 4.3, 3.9, 2.5, 1.6),
  test2_score = c(9.1, 9.1, 9.2, 11.1, 13.9, 14.5, 19.2, 19.3, 19.1, 18.8),
  stringsAsFactors = FALSE)
datatable(df) %>% formatStyle(
  'name',
  target = 'row',
  backgroundColor = styleEqual(c("Bob", "Ashley"), c('blue', 'red'))
)
```

The table looks like this: enter image description here

Upvotes: 2

Related Questions