Home > Blockchain >  Recursive magrittr piping / loop in gt package R
Recursive magrittr piping / loop in gt package R

Time:02-06

I'm trying to apply the data_color() function from the gt package to several columns in my data frame, but each with their own color palette domain. So far, what I have is:


df <- data.frame(Var1 = rnorm(30),
                 Var2 = rnorm(30),
                 Var3 = rnorm(30),
                 Var4 = rnorm(30),
                 Var5 = rnorm(30),
                 Var6 = rnorm(30))


mypals <- list()
for (i in 2:6){
  mypals[[i]] <- scales::col_bin(colpal,
                                 domain = c(min(df[,i]), max(df[,i])))
}

df %>%
  gt() %>%
  data_color(columns = 2, colors  = mypals[[2]]) %>%
  data_color(columns = 3, colors  = mypals[[3]]) %>%
  data_color(columns = 4, colors  = mypals[[4]]) %>%
  data_color(columns = 5, colors  = mypals[[5]]) %>%
  data_color(columns = 6, colors  = mypals[[6]])

Is there a way to do a "recursive" piping, something similar to this perhaps?

df %>%
  gt() %>% seq(2:6) %>% (function(x){
    data_color(columns = x, colors = mypals[[x]])
  }
    
  )

Thanks in advance for all your suggestions. I'm new to the gt package, so forgive me if there's an easier way to do this.

CodePudding user response:

I can' test this answer throughy, because I cant install this gt package, but I believe you are looking for the accumulate or reduce functions from the purrr package.

library(purrr)

my_data_color <- \(x, y, z) data_color(x, columns = y, colors = z[[y]])

reduce2(df %>% gt(),
            1:6,
            ~ my_data_color(x = .x,
                            y = .y,
                            z = mypals))

From the man page:

reduce() is an operation that combines the elements of a vector into a single value. The combination is driven by .f, a binary function that takes two values and returns a single value: reducing f over 1:3 computes the value f(f(1, 2), 3).

CodePudding user response:

One approach would be generate your statement and use eval(parse(text=<stment>)), as below:

eval(parse(text=paste(
  "df %>% gt() %>%",
  paste0("data_color(columns=",2:6,",color='",mypals,"')", collapse=" %>% ")
)))
  • Related