r - How to avoid promise already under evaluation warning for setting default argument as a function of another argument -
i've read other answers issues related "promise under evaluation" warning, unable see how can me avoid problem.
here have function 1 method, takes default argument value function of value.
myfun <- function(x, ones = null) { usemethod("myfun") } myfun.list <- function(x, ones = na) { data.frame(x = x[[1]], ones) } ones <- function(x) { rep(1, length(x)) }
so far, good:
myfun(list(letters[1:5])) ## x ones ## 1 na ## 2 b na ## 3 c na ## 4 d na ## 5 e na
but when define method sets default ones
argument function ones(x)
, error:
myfun.character <- function(x, ones = ones(x)) { myfun(as.list(x), ones) } myfun(letters[1:5]) ## error in data.frame(x = x[[1]], ones) : ## promise under evaluation: recursive default argument reference or earlier problems?
for various reasons, need keep argument name same function name (for ones
). how can force evaluation of argument within my fun.character
? need work (which does):
myfun(letters[1:5], 1:5) ## x ones ## 1 1 ## 2 2 ## 3 3 ## 4 4 ## 5 5
thanks!
one need deep r's (notorious) environments understand exactly, tries find ones
. problem located in way supplied , default arguments evaluated within function. can see this link r manual , explanation here.
the easy solution tell r it. save hassle. in case that's global environment.
changing method myfun.character
tell ones
in global environment:
myfun.character <- function(x, ones = get('ones', envir = globalenv())(x)) { myfun(as.list(x), ones) }
will enough here.
out:
myfun(letters[1:5]) # x ones #1 1 #2 1 #3 1 #4 1 #5 1 myfun(letters[1:5], 1:5) # x ones #1 1 #2 2 #3 3 #4 4 #5 5
Comments
Post a Comment