Reputation: 1165
I tried to colorize certain cells in a data frame (df_data) as highlighted below:
Inspired by the Introduction to Huxtable I tried the following:
library(huxtable)
as_hux(df_table) %>%
set_background_color(where(df_table["choice_mean"] < 2), 'red') %>%
set_background_color(where(df_table["N"] > 110), 'yellow')
The above commands colored the cells in the correct row – but only in the first column instead of the desired columns (N, choice_mean)/ the respective cells:
Many thanks for a brief reply and help!
Upvotes: 1
Views: 226
Reputation: 36
The problem is the where(DF_table["choice_mean"] < 2)
.
Here's what's going on, with some data so others can reproduce the problem (hint hint):
DF_table <- data.frame(choice_mean = c(1,2,3,1,3), N = c(100, 120, 100, 90, 100))
where(DF_table["choice_mean"] < 2)
## row col
## [1,] 1 1
## [2,] 4 1
You've only passed in part of the data frame to where
, and it correctly tells you that in that (1-column) part of the data frame, row 1 col 1 and row 4 col 1 are less than 2. This then gives the wrong info to set_background_color
.
You can get round this by using standard R subsetting:
DF_table <- as_hux(DF_table)
set_background_color(DF_table, DF_table$choice_mean < 2, 'choice_mean', 'red')
set_background_color(DF_table, DF_table$N > 110, 'N', 'yellow')
Here, DF_table$N > 110
specifies the rows, and 'N'
the column.
This is just the same as normal R subsetting:
DF_table[DF_table$N > 110, 'N']
## 120
Upvotes: 2