Function / Loop to Replace NA with values in adjacent columns in R
<p>I have a time series dataset with 1000 columns. Each row, is of course, a different record. There are some NA values that are scattered throughout the dataset.</p>

<p>I would like to replace each NA with either the adjacent left-value or the adjacent-right value, it doesn't matter which.</p>

<p>A neat solution and one which I was going for is to replace each NA with the value to its right, unless it is in the last column, in which case replace it with the value to its left.</p>

<hr>

<p><em>I was just going to do a for loop, but I assume a function would be more efficient. Essentially, I wasn't sure how to reference the adjacent values.</em></p>

<p>Here is what I was trying:</p>

<pre><code>for (entry in dataset) {
  if (any(is.na(entry)) == TRUE &amp;&amp; entry[,1:999]) {
    entry = entry[,1]
  }
  else if (any(is.na(entry)) == TRUE &amp;&amp; entry[,1000]) {
    entry = cell[,-1]
  }
}
</code></pre>

<p>As you can tell, I'm inexperienced with R :) Not really sure how you index the values to the left or right.</p>