Is there a way to generate the column defitions for color_tiles
dynamically? Here is my current approach which does not work correctly, as the tiles are always colored by the last class-column that I pass.
library(reactable)
library(reactablefmtr)
library(dplyr)
library(purrr)
tile_column <- function(x, ref_column, name, show_text = FALSE) {
colDef(
show = TRUE,
name = name,
cell = color_tiles(
x,
color_by = ref_column,
colors = c("red", "orange", "yellow", "limegreen", "green"),
box_shadow = TRUE,
show_text = show_text,
),
na = ""
)
}
data <- tibble(
name = paste("name", 1:10),
val1 = paste("val1", 1:10),
val2 = paste("val2", 1:10),
class1 = sample(1:5, 10, replace = TRUE),
class2 = sample(1:5, 10, replace = TRUE),
)
col_definitions1 <- list(
name = colDef(show = TRUE, name = "Name")
)
col_definitions2 <- list()
for (i in 1:2) {
col_definitions2 <- c(
col_definitions2,
list(tile_column(data, ref_column = paste0("class", i), name = paste("Column", i), show_text = TRUE))
)
}
col_definitions3 <- col_definitions2 |> set_names(paste0("val", 1:2))
col_definitions <- c(col_definitions1, col_definitions3)
# browser()
data %>%
reactable(
defaultColDef = colDef(show = FALSE),
columns = col_definitions
)
CodePudding user response:
Not sure what's the issue. But to make your code work you could switch to lapply
instead of using a for
loop. Just a guess, but as a similar issue is well known when creating ggplot2 inside a for loop the reason for the issue might be related to lazy evaluation.
library(reactable)
library(reactablefmtr)
library(dplyr)
set.seed(123)
col_definitions2 <- lapply(1:2, function(i) tile_column(data, ref_column = paste0("class", i), name = paste("Column", i), show_text = TRUE))
names(col_definitions2) <- paste0("val", 1:2)
col_definitions <- c(col_definitions1, col_definitions2)
data %>%
reactable(
defaultColDef = colDef(show = FALSE),
columns = col_definitions
)