Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R function calls other functions. I want user to choose whether to override default argument or not

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading