title: How to simplify data checking that iterates by rows and columns (two nested loops) with if_else
body: <pre><code>Q1 &lt;- c(1, 1, 2, 2)
  Q2_1 &lt;- c(3, 3, 3, 3)
  Q2_2 &lt;- c(3, 4, 2, 1)
  
  data &lt;- data.frame(cbind(Q1, Q2_1, Q2_2))
  </code></pre>
  
  <p>I need to do some data checking if values in Q1 variables do not appear in Q2 variables (in both Q2_1 and Q2_2) and I need the result in a single variable.
  For now I was using to nested for loops (for rows and columns) with if_else function from dplyr but it's quite a lot of code and I have to do similar checks multiple times. Is there any way to simplify the code?</p>
  
  <p>For now that what I'm doing: </p>
  
  <pre><code>Q2_index &lt;- grep("Q2_", names(data))
  
  data$Q2_error &lt;- 0 
  for(i in 1:dim(data)[1]){
      for(j in 1:length(Q2_index)){
          data$Q2_error[i] &lt;- if_else(data$Q2_error != 1 &amp; data$Q1 == data[, Q2_index[j]], 1, 0, 0)[i]
      }
  }
  </code></pre>
  
  <p>Second example:</p>
  
  <pre><code>ID &lt;- 1:3
  Q1_1 &lt;- 1:3
  Q1_2 &lt;- c(3, NA, 1)
  Q1_3 &lt;- c(4, 2, 1)
  Q2_1 &lt;- c(5, 2, 1)
  Q2_2 &lt;- c(1, NA, NA)
  Q2_3 &lt;- c(NA, NA, NA)
  
  data &lt;- data.frame(ID, Q1_1, Q1_2, Q1_3, Q2_1, Q2_2, Q2_3)
  
  Q1_index &lt;- grep("Q1_", names(data))
  Q2_index &lt;- grep("Q2_", names(data))
  
  data$Q1Q2error &lt;- 0
  for(i in 1:dim(data)[1]){
      for(j in 1:length(Q1_index)){
          data$Q1Q2error[i] &lt;- if_else(data[, Q1_index[j]] &gt;= 1 &amp; data[, Q2_index[j]] != data[, Q1_index[j]] &amp; is.na(data[, Q2_index[j]]), 0, 1, 1)[i]
    } 
  }
  </code></pre>
  
  <p>Evaluated conditions vary from check to check. As a result I need a single variable that indicates if I deal with an error so I can easily match the error to ID (so either 1 and 0 or TRUE, FALSE). Please notice that this is simplyfied example and I have to deal with around 10-20 Q1 or Q2 variables at the same time. </p>