Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding pattern in a matrix in R
    text
    copied!<p>I have a 8 x n matrix, for instance</p> <pre><code>set.seed(12345) m &lt;- matrix(sample(1:50, 800, replace=T), ncol=8) head(m) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 37 15 30 3 4 11 35 31 [2,] 44 31 45 30 24 39 1 18 [3,] 39 49 7 36 14 43 26 24 [4,] 45 31 26 33 12 47 37 15 [5,] 23 27 34 29 30 34 17 4 [6,] 9 46 39 34 8 43 42 37 </code></pre> <p>I would like to find a certain pattern in the matrix, for instance I would like to know where I can find a 37, followed in the next line by a 10 and a 29 and the line after by a 42</p> <p>This happens, for instance, in lines 57:59 of the above matrix</p> <pre><code>m[57:59,] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] *37 35 1 30 47 9 12 39 [2,] 5 22 *10 *29 13 5 17 36 [3,] 22 43 6 2 27 35 *42 50 </code></pre> <p>A (probably inefficient) solution is to get all the lines containing 37 with</p> <pre><code>sapply(1:nrow(m), function(x){37 %in% m[x,]}) </code></pre> <p>And then use a few loops to test the other conditions.</p> <p>How could I write an efficient function to do this, that can be generalized to any user-given pattern (not necessarily over 3 lines, with possible "holes", with variable number of values in each line etc).?</p> <p>EDIT: to answer various comments</p> <ul> <li>I need to find the EXACT pattern</li> <li>The order in the same row does not matter (if it makes things easier values can be ordered in each row)</li> <li>The lines have to be adjacent.</li> <li>I want to get the (starting) position of all the pattern returned (i.e., if the pattern is present multiple times in the matrix I want multiple return values).</li> <li>The user would enter the pattern via a GUI, I have yet to decide how. For instance, to search for the above pattern he may write something like </li> </ul> <p><code>37;10,29;42</code></p> <p>Where <code>;</code> represents a new line and <code>,</code> separates values on the same line. Similarly we may look for</p> <pre><code>50,51;;75;80,81 </code></pre> <p>Meaning 50 and 51 in line n, 75 in line n+2, and 80 and 81 in line n+3</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload