What is the difference between assign() and <<- in R?

前端 未结 3 1461
借酒劲吻你
借酒劲吻你 2020-11-27 22:00

The normal approach to writing functions in R (as I understand) is to avoid side-effects and return a value from a function.

contained <- function(x) {
          


        
3条回答
  •  醉话见心
    2020-11-27 22:15

    As pointed out by @John in his answer, assign lets you specify the environment specifically. A specific application would be in the following:

    testfn <- function(x){
    
        x_squared <- NULL
    
        escape <- function(x){
            x_squared  <<- x^2
            assign("x_times_x", x*x, envir = parent.frame(n = 1))
        }
    
        escape(x)
    
        print(x_squared)
        print(x_times_x)
    }
    

    where we use both <<- and assign. Notice that if you want to use <<- to assign to the environment of the top level function, you need to declare/initialise the variable. However, with assign you can use parent.frame(1) to specify the encapsulating environment.

提交回复
热议问题