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

前端 未结 3 1462
借酒劲吻你
借酒劲吻你 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:05

    According to the manual page here,

    The operators <<- and ->> cause a search to made through the environment for an existing definition of the variable being assigned.

    I've never had to do this in practice, but to my mind, assign wins a lot of points for specifying the environment exactly, without even having to think about R's scoping rules. The <<- performs a search through environments and is therefore a little bit harder to interpret.

    EDIT: In deference to @Dirk and @Hadley, it sounds like assign is the appropriate way to actually assign to the global environment (when that's what you know you want), while <<- is the appropriate way to "bump up" to a broader scope.

提交回复
热议问题