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

后端 未结 6 1205
别跟我提以往
别跟我提以往 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:41

    The <<- operator can also be useful for Reference Classes when writing Reference Methods. For example:

    myRFclass <- setRefClass(Class = "RF",
                             fields = list(A = "numeric",
                                           B = "numeric",
                                           C = function() A + B))
    myRFclass$methods(show = function() cat("A =", A, "B =", B, "C =",C))
    myRFclass$methods(changeA = function() A <<- A*B) # note the <<-
    obj1 <- myRFclass(A = 2, B = 3)
    obj1
    # A = 2 B = 3 C = 5
    obj1$changeA()
    obj1
    # A = 6 B = 3 C = 9
    

提交回复
热议问题