How to generalize a function?

Hi,

I can't run your code, as you did not supply a real reprex, but I think I know what you were looking for. For future reference: A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

library(dplyr)
library(purrr)

BF_table=function(BF_output){
  
  #Put code here, now returns random data frame
  myTable = data.frame(x = BF_output, y = runif(5))
  return(myTable)
}

glue_BFs=function(...){
  
  #No need to replace any code (should work...)
  newTable = map_df(list(...), BF_table)
  return(newTable)
}


glue_BFs(1,2,3)
#>    x          y
#> 1  1 0.34722334
#> 2  1 0.48636603
#> 3  1 0.50046496
#> 4  1 0.15819100
#> 5  1 0.55372418
#> 6  2 0.30276565
#> 7  2 0.63276609
#> 8  2 0.76074751
#> 9  2 0.51630210
#> 10 2 0.91425049
#> 11 3 0.36733847
#> 12 3 0.54266198
#> 13 3 0.59673181
#> 14 3 0.09400021
#> 15 3 0.52223592

Created on 2020-08-03 by the reprex package (v0.3.0)

The clue to the whole thing is the (...) argument in the glue_BFs function. These three dots mean it will take and number of trailing arguments and put them in a vector. So this can go from 0 to Inf (in theory). If you need to pass any named arguments, you can combine the two, but remember that the position of placing the ... will define which arguments go where.

... last

test = function(arg1, ...){
  print(arg1)
  print(c(...))
}

test(1,2,3)

In this function, the first argument will always be arg1 (e.g. it is mandatory and must be set) In the example case arg1 = 1, and ... is 2 and 3. This way of writing is best when your function has one or more mandatory arguments, followed by the list of trailing arguments.

... first

test = function(..., arg1 = NULL){
  print(arg1)
  print(c(...))
}

test(1,2,3)
test(1,2, arg1 = 3)

In this case, all arguments are considered trailing, thus will go in the ... unless you specify the argument explicitly. So in the first case, 1,2 and 3 are all ... and arg1 is undefined, in the second 1 and 2 are in ... and arg1 = 3. This approach is best if the arguments that have a name are optional, and thus are not often set.

Hope this helps,
PJ

2 Likes