Get a matrix as Output if a condition for a single value is met in R.

R ProgrammingServer Side ProgrammingProgramming

If we want to check a condition and the Output based on that condition needs to be a matrix then we can use if else function in R.

For Example, if we have a value say V = 5 and we want to get matrix M1 if V is equal to 5 and matrix M2 if V is not equal to 5 then we can use the below command −

if (V == 5) M1 else M2

Example

Following snippet creates a sample matrices −

M1<-matrix(rpois(80,10),ncol=4)
M1

The following matrix is created −

    [,1] [,2] [,3] [,4]
[1,]  5   6    11    7
[2,]  8   13    7   11
[3,]  9   7    11   13
[4,]  11  14    9   12
[5,]  8   14    9    9
[6,]  9   7    11    7
[7,]  12  9    16   10
[8,]  4   11    9    7
[9,]  14  15   11    6
[10,] 12  5     3    8
[11,] 10  8     9   10
[12,] 11  7    11   10
[13,] 17  12    6    7
[14,] 15  7     7   13
[15,] 16  15    5   17
[16,] 7   7     9    9
[17,] 8   14    5    6
[18,] 14  8     8    7
[19,] 9   8     8   14
[20,] 13  10   12   10

To get a matrix as Output if a condition for a single value is met in R, on the above created matrix, add the following code to the above snippet −

M1<-matrix(rpois(80,10),ncol=4)
M2<-matrix(rpois(80,1),ncol=4)
M2

The following matrix is created −

    [,1] [,2] [,3] [,4]
[1,]  2    0    2   4
[2,]  0    1    1   2
[3,]  0    0    0   0
[4,]  0    3    1   1
[5,]  0    1    1   0
[6,]  0    1    2   1
[7,]  0    1    0   0
[8,]  2    0    2   1
[9,]  0    1    0   0
[10,] 0    2    1   1
[11,] 1    0    1   2
[12,] 0    1    0   1
[13,] 0    2    0   0
[14,] 1    0    2   0
[15,] 0    0    0   1
[16,] 1    1    1   0
[17,] 0    1    2   1
[18,] 1    0    1   1
[19,] 0    2    1   0
[20,] 2    2    1   2

To get matrix as Output Conditional_Value is equal to or not equal to 5 on the above created data frame, add the following code to the above snippet −

M1<-matrix(rpois(80,10),ncol=4)
M2<-matrix(rpois(80,1),ncol=4)
Conditional_Value<-2
if (Conditional_Value == 5) M1 else M2

The following matrix is created −

   [,1] [,2] [,3] [,4]
[1,]  2   0   2    4
[2,]  0   1   1    2
[3,]  0   0   0    0
[4,]  0   3   1    1
[5,]  0   1   1    0
[6,]  0   1   2    1
[7,]  0   1   0    0
[8,]  2   0   2    1
[9,]  0   1   0    0
[10,] 0   2   1    1
[11,] 1   0   1    2
[12,] 0   1   0    1
[13,] 0   2   0    0
[14,] 1   0   2    0
[15,] 0   0   0    1
[16,] 1   1   1    0
[17,] 0   1   2    1
[18,] 1   0   1    1
[19,] 0   2   1    0
[20,] 2   2   1    2
raja
Published on 03-Nov-2021 09:58:55

Advertisements