How do you use “<<-” (scoping assignment) in R?

后端 未结 6 1287
别跟我提以往
别跟我提以往 2020-11-22 11:16

I just finished reading about scoping in the R intro, and am very curious about the <<- assignment.

The manual showed one (very interesting) examp

6条回答
  •  旧巷少年郎
    2020-11-22 11:34

    On this subject I'd like to point out that the <<- operator will behave strangely when applied (incorrectly) within a for loop (there may be other cases too). Given the following code:

    fortest <- function() {
        mySum <- 0
        for (i in c(1, 2, 3)) {
            mySum <<- mySum + i
        }
        mySum
    }
    

    you might expect that the function would return the expected sum, 6, but instead it returns 0, with a global variable mySum being created and assigned the value 3. I can't fully explain what is going on here but certainly the body of a for loop is not a new scope 'level'. Instead, it seems that R looks outside of the fortest function, can't find a mySum variable to assign to, so creates one and assigns the value 1, the first time through the loop. On subsequent iterations, the RHS in the assignment must be referring to the (unchanged) inner mySum variable whereas the LHS refers to the global variable. Therefore each iteration overwrites the value of the global variable to that iteration's value of i, hence it has the value 3 on exit from the function.

    Hope this helps someone - this stumped me for a couple of hours today! (BTW, just replace <<- with <- and the function works as expected).

提交回复
热议问题