Search code examples
rfor-loopoptimizationvectorsubtraction

How do i get the same result without using a for loop in R


I hear for loops in R are slow so I was wondering how to simplify this to speed things up. I want to subtract 1 from every element in connections, but if it is already zero, i don't want to keep subtracting and make it negative.

for(i in 1:length(connections)) {
    if(connections[i] > 0) {
      connections[i] = connections[i] - 1
    }
    if(connections[i] < 0) {
      connections[i] = 0
    }
  }

Solution

  • One way would be to keep the max of (connections - 1) and 0.

    pmax(connections - 1, 0)