r - Function flow: why does this function return 20 -
suppose have function called l:
l <- function(x) x + 1 then define function, m, within m, redefine l:
m <- function() { l <- function(x) x*2 l(10) } m() why m return x*2, , not x+1?
if you're not sure what's going on, can helpful add print statements. let's add few print statements code -- 1 before m called, 2 inside m function, , 1 after m called:
l <- function(x) x + 1 m <- function() { print(l) l <- function(x) x * 2 print(l) l(10) } print(l) # function(x) x + 1 m() # function(x) x + 1 # function(x) x * 2 # <environment: 0x7f8da5ac3b58> # [1] 20 print(l) # function(x) x + 1 before m called , @ top of m, l defined function returns x+1. however, within m change l new function, 1 returns x*2, indicated second print statement in function. result, calling l(10) returns 20. once leave function original l definition (x+1) because x*2 version defined function. concept of function being defined locally called name masking.
Comments
Post a Comment