title: Loop of for to replace missing cases conditional on the next variable (tidyverse solution will be appreciated)
body: <p>As always, I'm here after checking tons of information about coding.
  Let me explain the situation I'm faced right now: I'm working on a psychological scale that aims to access child development. In this scale, <strong>we have no possibility of missing cases</strong>, only 0, 1, or 2. Unfortunately, people coded some values with missing and I'm struggling to fix that.</p>
  
  <p>All missing cases must be filled with the following criteria:</p>
  
  <p>if the <strong>actual variable is missing</strong> <strong>AND</strong>
  If the next variable is <strong>2</strong>, then the missing will be "2";
  if the next variable is <strong>1</strong>, then the missing will be "1",
  if the next variable is <strong>0</strong>, then the missing will be "0"</p>
  
  <p>The last column will not be included in the script. </p>
  
  <p>Pretty easy to talk about it, but it's challenging me to code that.</p>
  
  <p>My intuitive coding says something like that:</p>
  
  <pre><code>for (i in 1:ncol(ds)) {
    if(is.na(ds[i]) &amp; ds[i+1] == "2") ds[i] == "2"
  }
  </code></pre>
  
  <p>And the code you can reproduce to work on is:</p>
  
  <pre><code>ds &lt;- data.frame(x1 = rep(sample(0:2),5), 
                   x2 = sample(0:2),
                   x3 = sample(0:2),
                   x4 = sample(0:2))
  ds[ds == 0] &lt;- NA
  
  for (i in 1:ncol(ds)) {
    if(is.na(ds[i]) &amp; ds[i+1] == "2") ds[i] == "2"
  }
  </code></pre>
  
  <p>Just to clarify, I know tidyverse (broom) is really useful for situations like that and I'll be happy if someone could explain that using tidyverse environment.</p>
  
  <p>Thanks a lot!</p>
  
  <p><strong>Edited</strong>: If you are here to check the answer, feel welcome! But you can go as well to <a href="https://stackoverflow.com/questions/38463511/function-loop-to-replace-na-with-values-in-adjacent-columns-in-r">Function / Loop to Replace NA with values in adjacent columns in R</a> . Thanks much!</p>