Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving arguments of a function call with default values in R

Tags:

parsing

r

Is there a way to retrieve function arguments from an evaluated formula that are not specified in the function call?

For example, consider the call seq(1, 10). If I wanted to get the first argument, I could use quote() and simply use quote(seq(1,10))[[1]]. However, this only works if the argument is defined at the function call (instead of having a default value) and I need to know its exact position.

In this example, is there some way to get the by argument from seq(1, 10) without a lengthy list of if statements to see if it is defined?

like image 891
Jon Claus Avatar asked Feb 16 '23 07:02

Jon Claus


1 Answers

The first thing to note is that all of the named arguments you're after (from, to, by, etc.) belong to seq.default(), the method that is dispatched by your call to seq(), and not to seq() itself. (seq() itself only has one formal, ...).

From there you can use these two building blocks

## (1) Retrieves pairlist of all formals
formals(seq.default)
# [long pairlist object omitted to save space]

## (2) Matches supplied arguments to formals
match.call(definition = seq.default, call = quote(seq.default(1,10)))
# seq.default(from = 1, to = 10)

to do something like this:

modifyList(formals(seq.default),
           as.list(match.call(seq.default, quote(seq.default(1,10))))[-1])
# $from
# [1] 1
# 
# $to
# [1] 10
# 
# $by
# ((to - from)/(length.out - 1))
# 
# $length.out
# NULL
# 
# $along.with
# NULL
# 
# $...
like image 92
Josh O'Brien Avatar answered Apr 07 '23 11:04

Josh O'Brien