I have a main function that decides which secondary function it is going to call (and may call several of them). If user specifies an argument, the default of the secondary functions is overridden; otherwise, default is used. How to implement that into the main function?
Ex:
main <- function(x, f, d = ?) do.call(f, args = list(x = x, d = d))
f1 <- function(x, d = 0) x + d
f2 <- function(x, d = 1) x * d
I want to write the default for d in main so that, in case the user does not specify any value, it will pass d=0 to f1 and d=1 to f2.
>Solution :
You could use the formals() function to get the default value of parameter d in the specified function.
main <- function(x, f, d = formals(f)$d) do.call(f, args = list(x = x, d = d))
f1 <- function(x, d = 0) x + d
f2 <- function(x, d = 1) x * d
main(3, f1)
#> [1] 3
main(3, f1, 4)
#> [1] 7
main(3, f2)
#> [1] 3
main(3, f2, 4)
#> [1] 12
Created on 2024-06-19 with reprex v2.1.0