Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract function parameters and default values from any function

Is there a way to extract the parameters and their respective default values of any given function from outside the function?

For example, given:

myfunc <- function(a, b = 1) { print(c(a, b)) }

I'm looking for some function that will return:

list(a = NULL, b = 1) 

or some variation thereof.

like image 315
joper Avatar asked Apr 10 '16 17:04

joper


People also ask

How do we provide the default values of function parameters?

In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.

How do you extract parameters in Python?

Extract a Python parameter in place Do one of the following: Press Ctrl+Alt+P . Choose Refactor | Extract | Parameter from the main menu. Choose Refactor | Extract | Parameter from the context menu.

What is default parameter in function explain with example?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument.


1 Answers

You are looking for formals().

formals(myfunc)
# $a
#
#
# $b
# [1] 1

If you needed NULL for a, you could do some checking. a will be of the "name" class and empty.

lapply(formals(myfunc), function(x) if(is.name(x) & !nzchar(x)) NULL else x)
# $a
# NULL
#
# $b
# [1] 1
like image 178
Rich Scriven Avatar answered Oct 12 '22 09:10

Rich Scriven