0

I have a function I would like to keep everything fixed apart form a single argument.

    ls <- score_model_compound(data, pred, tmp$Prediction, score= "log")
    bs <- score_model_compound(data, pred, tmp$Prediction, score="Brier")
    ss <- score_model_compound(data, pred, score="spherical")

what I would like is something like

ls = data.frame()
    ls <- score_model_compound(data, pred, score= c("log", "Brier", "spherical"))

is there a function I can use, like apply(), which lets me do this?

Thank you

  • 3
    `lapply(setNames(nm=c("log", "Brier", "spherical")), function(sc) score_model_compound(data, pred, score=sc))`. This will return a named list, each element being the result from one call to the function. (I used `setNames(nm=.)` as one way to name the results, so that `results[["log"]]` will work as expected; there are other ways.) – r2evans Jul 20 '21 at 13:22

2 Answers2

0

You can create some kind of wrapping function with only the first argument being the one you want to vary and then pass it to lapply:

## Creating the wrapping function
my.wrapping.function <- function(score, data, pred, tmp) {
    return(score_model_compound(data  = data,
                                pred  = pred,
                                tmp   = tmp,
                                score = score))
}

## Making the list of variables
my_variables <- as.list(c("log", "Brier", "spherical"))

## Running the function for all the variables (with the set specific arguments)
result_list <- lapply(my_variables,
                      my.wrapping.function,
                      data = data, pred = pred, tmp = tmp$Prediction)

And finally, to transform it into a data.frame (or matrix), you can use the do.call(cbind, ...) function on the results:

## Combining the results into a table
my_results_table <- do.call(cbind, result_list)

Does that answer your question?

Thomas Guillerme
  • 1,747
  • 4
  • 16
  • 23
0

mapply() to the rescue:

score_v = c('spherical', 'log', 'Brier')

l = mapply(
  score_model_compound, # function
  score = score_v, # variable argument vector
  MoreArgs = list(data = data, # fixed arguments
                  pred = pred),
  SIMPLIFY = FALSE # don't simplify
) 

You probably have to tweak it a little yourself, since you didn't provide a reproducible example. mapply(SIMPLIFY = FALSE) will output you a list. If the function returns data.frame's the resulting list of data.frame's can subsequently be bound with e.g. data.table::rbindlidst().


Alternatively you could just use a loop:

l = list()
for (i in seq_along(score_v)) {
  sc = score_v[i]
  message('Modeling: ', sc)
  smc = score_model_compound(data, pred, score = sc)
  l[[i]] = smc
  names(l)[i] = sc
}
andschar
  • 3,504
  • 2
  • 27
  • 35