Search code examples
rlimitmin

Constrain lower limit of the result of a subtraction


I want to subtract the values in a vector from a scalar. However, if the result is lower than zero I want to set the result to zero.

I have tried using max, but it doesn't give me the expected result

s
# [1]  750.0  975.0 1125.0 1237.5 1312.5 1400.0

max(1050 - s, 0)
# [1] 300

I expect result to be c(300, 150, 0, 0, 0, 0)


Solution

  • I suggest pmax:

    pmax(1050 - s, 0)
    # [1] 300  75   0   0   0   0