title: Compute formula by selecting the first and the last non-missing values in dynamic width in one column to fill in the NAs over the widith
body: <p>I have data of two variables gert and NAV. I need to fill in the missing NAs of NAV variable. 
  To compute those missing NAs, I need to use the first and last non-missing NAV values and the return values (gret) to do the imputation. </p>
  
  <p><a href="https://i.stack.imgur.com/93l2h.png" rel="nofollow noreferrer">enter image description here</a></p>
  
  <p>the width between the two in red colored non-missing NAV values is n = 3, and the first and last non-missing values are 6830228.05 and 14277802.16</p>
  
  <p>to impute the first missing NAV value (in this specific width) which has a return of -0.2, I do the following: </p>
  
  <p>first and for each width n, I compute a factor called F, after that I use it over all NAs within this specific width n. </p>
  
  <p>So, the value of the first missing NAV would be = <strong>F * 6830228.05 * (1 - 0.2)</strong> </p>
  
  <p>The value that I imputed above, I use it then to impute the second missing NAV value which has a return of +1.58  and which would be = F * (<strong>F * 6830228.05 * (1 - 0.2)</strong>) * (1 + 1.58). </p>
  
  <p>for the the third missing value, I do the same and I use the previous imputed NAV.</p>
  
  <p>the formale of F for this width n = 3 is as following: (note: I use all values of return in this width to compute F and only I use the first and last non-missing NAV values) </p>
  
  <p><a href="https://i.stack.imgur.com/i9tw6.png" rel="nofollow noreferrer">enter image description here</a></p>
  
  <p>I replicate this process by moving down to the second width n = 2 and for which, the first and last non-missing NAV values are 15030901.93 and 16911789.99 (colored green)</p>
  
  <p>the formale of F for this width n = 2 is: </p>
  
  <p><a href="https://i.stack.imgur.com/cRc0N.png" rel="nofollow noreferrer">enter image description here</a> </p>
  
  <p>and so on until the end of this variable series. </p>
  
  <p>May someone help me please me in coding this in R? </p>
  
  <p>Many thanks</p>