Why is using `

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)

Leave a Comment