Why does evaluating an expression in system.time() make variables available in global environment?

后端 未结 3 1599
挽巷
挽巷 2021-01-11 15:35

Can somebody please explain what happens when an expression is evaluated in system.time? In particular, why are any variables that are declared in the ex

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 16:02

    I think the expr is evaluated before handling that to the function. POC example:

    > st <- function(expr){
    +   eval(parse(text=expr))
    + }
    > 
    > st('aa <- 1')
    > aa
    Error: object 'aa' not found
    

    So I think the function gets expr as only aa. Another example:

    > st <- function(expr){
    +   str(expr)
    + }
    > 
    > st(aa <- 1)
     num 1
    

    I might be wrong, it is rather an intuition :) But thanks, that is a good puzzle!


    Update:

    > system.time(a <- 1)
       user  system elapsed 
          0       0       0 
    > a
    [1] 1
    > rm(a)
    > fn <- function() a <- 1
    > system.time(fn())
       user  system elapsed 
          0       0       0 
    > a
    Error: object 'a' not found
    

提交回复
热议问题