How can I create a list with the concatenation of a character vector and a function?

33 views Asked by At

I am formatting tables using the package formattable in R. This way I can apply an arbitrary function to each column like this. First, define the function and later on apply it to each column manually as a list as you can see below:

# formatting function to be applied
improvement_formatter <- 
  formatter("span", 
            style = x ~ style(
              color = ifelse(x > 0, "green", "red")))

formattable(desc_vars, align = rep("c", length(model_variables)),
            list(
            `mbmi` = improvement_formatter,
            `fbmi` = improvement_formatter,
            `parity` = improvement_formatter,
            `smok` = improvement_formatter,
            `ethn` = improvement_formatter,
            `mses` = improvement_formatter,
            `medu` = improvement_formatter,
            `mage` = improvement_formatter,
            `fses` = improvement_formatter,
            `fedu` = improvement_formatter,
            `fage` = improvement_formatter,
            `sex` = improvement_formatter,
            `mother_BMI_gscore` = improvement_formatter
            ))

The thing is that I would like to automatize the creation of a list because, with tables with lots of columns, it becomes a tedious job to fulfill all the columns like this.

I thought about creating the concatenation with something like this, however I just do create a list of characters and not the proper format to pass inside this list:

as.list(paste(paste0("`", outcome_vars, "`"), "=", "improvement_formatter"))

Any Ideas on how this could be solved?

Thank you very much!!!

1

There are 1 answers

0
Andrea Barghetti On

could this work?

sapply(USE.NAMES = F, outcome_vars, function(name) {
  setNames(c(improvement_formatter), name)
})