R: default value using other argument modified when other argument modified -
when defining default argument y r function being equal other argument x. ex: function(x,y=x). found if change other argument (x) before using default argument (y), changes value of y.
i understand has "delayed copying until modified" desired behavior?
hereafter full example:
oh_my <- function(x, y=x){ x <- rev(x) y <- rev(y) # value of y here rev of initial x! print(y) } oh_my(1:5) [1] 1 2 3 4 5
an easy solution be:
ok <- function(x, y=null){ if(is.null(y)){ y<-x } x <- rev(x) y <- rev(y) print(y) } ok(1:5) [1] 5 4 3 2 1
but fact default obvious in first option (including in automatically generated files).
an other solution be:
pfiouu <- function(x, y=x){ y <- rev(y) # value of y here rev of initial x! x <- rev(x) print(y) } pfiouu(1:5)
[1] 5 4 3 2 1
but seems awkward me pfiouu , oh_my give different results 2 exchanged lines not mention explicitly each others variables , yet yield different results!
am missing practice keep default obvious , avoid kind of fall-trap?
as suggested mrflick, adding force(y) @ start of function allows force evaluation of y , prevents issues that. being desirable behavior in such high level programming language r remains open though.
no_surprise<- function(x, y=x){ force(y) x <- rev(x) y <- rev(y) print(y) } no_surprise(1:5) [1] 5 4 3 2 1
as expected.
wiki
Comments
Post a Comment