title: Replace NA row with non-NA value from previous row and certain column
body: <p>I have a matrix, where rows can have NA's for all columns. I want to replace these NA rows with previous row's non-NA value and K-th column.</p>
  
  <p>For example, this matrix:</p>
  
  <pre><code>      [,1] [,2]
   [1,]   NA   NA
   [2,]   NA   NA
   [3,]    1    2
   [4,]    2    3
   [5,]   NA   NA
   [6,]   NA   NA
   [7,]   NA   NA
   [8,]    6    7
   [9,]    7    8
  [10,]    8    9
  </code></pre>
  
  <p>Must be transformed to this non-NA matrix, where we use 2-th column for replacement:</p>
  
  <pre><code>      [,1] [,2]
   [1,]   NA   NA
   [2,]   NA   NA
   [3,]    1    2
   [4,]    2    3
   [5,]    3    3
   [6,]    3    3
   [7,]    3    3
   [8,]    6    7
   [9,]    7    8
  [10,]    8    9
  </code></pre>
  
  <p>I wrote a function for this, but using loop:</p>
  
  <pre><code># replaces rows which contains all NAs with non-NA values from previous row and K-th column
  na.replace &lt;- function(x, k) {
      cols &lt;- ncol(x)
      for (i in 2:nrow(x)) {
          if (sum(is.na(x[i - 1, ])) == 0 &amp;&amp; sum(is.na(x[i, ])) == cols) {
              x[i, ] &lt;- x[i - 1 , k]
          }
      }
      x
  }
  </code></pre>
  
  <p>Seems this function works correct, but I want to avoid these loops. Can anyone advice, how I can do this replacement without using loops?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p><a href="https://stackoverflow.com/users/1838509/agstudy">agstudy</a> suggested it's own vectorized non-loop solution:</p>
  
  <pre><code>na.replace &lt;- function(mat, k){
    idx       &lt;-  which(rowSums(is.na(mat)) == ncol(mat))
    mat[idx,] &lt;- mat[ifelse(idx &gt; 1, idx-1, 1), k]
    mat
  }
  </code></pre>
  
  <p>But this solution returns different and wrong results, comparing to my solution with loops. Why this happens? Theoretically loop and non-loop solutions are identical.</p>