Environments in R, mapply and get

前端 未结 3 837
深忆病人
深忆病人 2021-01-22 17:51

Let x<-2 in the global env:

x <-2 
x
[1] 2

Let a be a function that defines another x locally and

3条回答
  •  广开言路
    2021-01-22 18:38

    R is lexically scoped, not dynamically scoped, meaning that when you search through parent environments to find a value, you are searching through the lexical parents (as written in the source code), not through the dynamic parents (as invoked). Consider this example:

    x <- "Global!"
    fun1 <- function() print(x)
    fun2 <- function() {
      x <- "Local!"
      fun1a <- function() print(x)
      fun1()           # fun2() is dynamic but not lexical parent of fun1()
      fun1a()          # fun2() is both dynamic and lexical parent of fun1a() 
    }
    fun2()
    

    outputs:

    [1] "Global!"
    [1] "Local!"
    

    In this case fun2 is the lexical parent of fun1a, but not of fun1. Since mapply is not defined inside your functions, your functions are not the lexical parents of mapply and the xs defined therein are not directly accessible to mapply.

提交回复
热议问题