Home > Mobile >  How to create an "if-else" condition?
How to create an "if-else" condition?

Time:04-03

I have this script:

sqmat <- structure(c(12, 68, 1, 31, 5, 7, 25, 17, 1, 25, 17, 1, 31, 5, 
7), .Dim = c(3L, 5L))

sqmat_2 <- structure(c(52, 4, 1, 31, 26, 22, 52, 4, 1, 23, 55, 12, 31, 26, 
22), .Dim = c(3L, 5L))

I need an "if-else" condition:

If the output row=1, col=1 in sqmat_2 (52) is > then twice output row=1, col=1 in sqmat (2 x 12) => give me "O". Else (if 52 <= 2 x 12) give me "C".

Point by point of the two matrices sqmat and sqmat_2; and display the results in a matrix. How can I do? Thanks for helping me!

CodePudding user response:

We can use ifelse with the logical condition specified in 'test' and the 'yes' and 'no' as the values 'O' and 'C'. It is recommended to have equal lengths for the arguments 'test', 'yes', 'no'. In this case the 'yes' and 'no' are single element, which gets recycled

ifelse(sqmat_2 > (2 * sqmat), "O", "C")
    [,1] [,2] [,3] [,4] [,5]
[1,] "O"  "C"  "O"  "C"  "C" 
[2,] "C"  "O"  "C"  "O"  "O" 
[3,] "C"  "O"  "C"  "O"  "O" 
  • Related