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

后端 未结 2 619
日久生厌
日久生厌 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: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)
    

提交回复
热议问题