I want to check a matrix to see if there exist a fixed pattern "xxxx" or "yyyy", (my matrix can have sequence of either 4 x's or 4 y's, not both at the same time. unless it is less than 4). Then if for example a sequence of 4 x exists, match <- "x", otherwise match <- "y". I want to check it row-wise, column-wise and (anti)diagonal-wise.
The main problem is with the last part, to assign "x" or "y" to the variable "match".
An example of my matrix is:
m <- matrix(NA, 6, 7)
m[6,2:5] <- "x"
I tried as below for x and y:
r <- apply(m, 1, paste, collapse="")
c <- apply(m, 2, paste, collapse="")
if (grepl("xxxx", r, fixed = TRUE) |
grepl("xxxx", c, fixed = TRUE)){
match <- "x"}
else if(grepl("yyyy", r, fixed = TRUE)|
grepl("yyyy", c, fixed = TRUE)){
match <- "y"}
However, it does not work since "grepl" returns a logical vector and it only checks if the first element is true. I've been struggling to find a way for 4 days already, could not even think of a way to try to find this pattern diagonal wise.
I am new to programming with R, would very much appreciate any help.