Issue:
I want to use a function default_arg() to access the default value of arg in the context of a function func. However, I'd also like this function to be clever enough to guess which function and which argument I want in a couple of cases:
Case 1 - Used With Explicit Arguments:
tester_1 <- function(x = 1, y = 2, z = 3) {
x * y + z
}
default_arg(x, tester_1) # this would evaluate to 1
Case 2 - Used Within a Function Body
tester_2 <- function(x = 1, y = 2, z = 3) {
x_default <- default_arg(x) # this would evaluate to 1
if(x < x_default) {
stop(paste("x should be greater or equal to default value:", x_default))
}
x * y + z
}
Case 3 - Used as a Parameter:
tester_1(
x = 2,
y = 1,
z = default_arg() # This would evaluate to 3
)
Current Approach:
I'm able to create something that works in cases 1 and 2, but I'm unsure how to approach Case 3. Here is the approach I'm using currently, using some functions from rlang:
default_arg <- function(arg, func = sys.function(sys.parent())) {
formals(func)[[as_name(enquo(arg))]]
}