Function If in R

I have a question and I would like to share it to see if anyone can help me.
I'm working on R with a matrix called matriz_diferencia . It has 3 rows of which one is empty and 96 columns. What I'm trying to do, is to complete that third row with values that arise from a conditional. If the value of the second row is <0 , the value should be 0 , otherwise it would be:

In this case it is not necessary to go through a cycle, R is "used" to working with vectors and matrices, which makes things much simpler in that sense.

We seek to update the third row with two different criteria, one way is not to worry about the if and to update directly in two steps, the first one, applying the calculation that you have given and in the second we set to zero those cases where the value of row 2 is less than zero:

This: (matriz_diferencia[2,] - matriz_diferencia[1,]) / matriz_diferencia[1,] is arithmetic with vectors that naturally manages R, what we say is: add each "cell" of row 2 with each "cell" of row 1 and divide it again by the values of the cell 1, the return will be another vector with the n values corresponding to each "cell".

The second pass: matriz_diferencia[3, matriz_diferencia[2,] < 0] <- 0 we set each value of row 3 in 0 if the same value in row 2 is less than 0

Anyway, if you wanted to solve everything in a single sentence, you could use the vectorized ifelse() function that works directly on vectors: