Function If in R

1

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:

(matriz_diferencia[2,x] - matriz_diferencia[1,x]) / matriz_diferencia[1,x]

I found a way to do it using a for and an if:

for(x in 1:96) {
    if(matriz_diferencia[2,x]<0) {
        matriz_diferencia[3,x]=0
    } else {
        matriz_diferencia[3,x]<-(matriz_diferencia[2,x] - 
            matriz_diferencia[1,x]) / matriz_diferencia[1,x]}
}

My query is the following: How could this be done using the apply function? Is there any other alternative to not use for?

    
asked by dami 30.10.2018 в 17:19
source

1 answer

2

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,])
    
answered by 30.10.2018 в 18:14