tsostarics / contrastable

Contrast Coding Utilities
https://tsostarics.github.io/contrastable/
Other
0 stars 0 forks source link

Pass `n_levels` to first function parameter #12

Closed tsostarics closed 11 months ago

tsostarics commented 11 months ago

Currently, set_contrasts and related functions can use external contrast coding schemes like so:

foo <- function(n) contr.sum(n)
foo2 <- function(n_levels) contr.sum(n_levels)

# Both of these are fine
set_contrasts(df, varName ~ foo)
set_contrasts(df, varName ~ foo2)

But if the named argument isn't n or n_levels then it doesn't work

foo3 <- function(boo) contr.sum(boo)

# Doesn't work
set_contrasts(df, varName ~ foo3)

In the definition for .bundle_params(), we can add the desired function as an optional argument then extend this block:

n_levels <- length(labels[[1]])
other_args <- rlang::dots_list(...)[['other']]
params <- list(n = n_levels)

such that if a function is passed, we can check whether n exists and if not, look up the name of the first parameter and set n_levels to that. Basically something like:

function_parameters <- names(formals(foo))
par_name <- "n"
if (!"n" %in% function_parameters)
  par_name <- function_parameters[1L]

params <- setNames(list(n_levels), par_name)