Why is using `<<-` frowned upon and how can I avoid it?

后端 未结 2 612
日久生厌
日久生厌 2020-11-28 13:19

I followed the discussion over HERE and am curious why is using<<- frowned upon in R. What kind of confusion will it cause?

I also would like some

相关标签:
2条回答
  • 2020-11-28 13:25

    You can think of <<- as global assignment (approximately, because as kohske points out it assigns to the top environment unless the variable name exists in a more proximal environment). Examples of why this is bad are here:

    Examples of the perils of globals in R and Stata

    0 讨论(0)
  • 2020-11-28 13:37

    First point

    <<- is NOT the operator to assign to global variable. It tries to assign the variable in the nearest parent environment. So, say, this will make confusion:

    f <- function() {
        a <- 2
        g <- function() {
            a <<- 3
        }
    }
    

    then,

    > a <- 1
    > f()
    > a # the global `a` is not affected
    [1] 1
    

    Second point

    You can do that by using Reduce:

    Reduce(function(a, b) {a[a==b] <- a[a==b]-1; a}, 2:6, df)
    

    or apply

    apply(df, c(1, 2), function(i) if(i >= 2) {i-1} else {i})
    

    But

    simply, this is sufficient:

    ifelse(df >= 2, df-1, df)
    
    0 讨论(0)
提交回复
热议问题