First of all, we put together a smaller example than yours, only for didactic purposes:
set.seed(1)
matriz_diferencia <- matrix(c(rnorm(2 * 4 ), rep(0, 4)), nrow = 3, byrow = TRUE)
matriz_diferencia
[,1] [,2] [,3] [,4]
[1,] -0.6264538 0.1836433 -0.8356286 1.5952808
[2,] 0.3295078 -0.8204684 0.4874291 0.7383247
[3,] 0.0000000 0.0000000 0.0000000 0.0000000
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:
matriz_diferencia[3, ] <- (matriz_diferencia[2,] - matriz_diferencia[1,]) / matriz_diferencia[1,]
matriz_diferencia[3, matriz_diferencia[2,] < 0] <- 0
matriz_diferencia
[,1] [,2] [,3] [,4]
[1,] -0.6264538 0.1836433 -0.8356286 1.5952808
[2,] 0.3295078 -0.8204684 0.4874291 0.7383247
[3,] -1.5259889 0.0000000 -1.5833082 -0.5371820
Detail:
- 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:
matriz_diferencia[3, ] <- ifelse(matriz_diferencia[2,] < 0,
0,
(matriz_diferencia[2,] - matriz_diferencia[1,]) / matriz_diferencia[1,])