title: R: Copying value for one type of group and year downwards and upwards
body: <p>I created a simplified version of my data since my actual data is too large to be include here.</p>
  <pre><code>structure(list(Name = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, 
  &quot;C&quot;, &quot;C&quot;, &quot;C&quot;, &quot;C&quot;), Category = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
  2L, 2L, 2L, 2L, 2L), Year = c(2018L, 2019L, 2020L, 2021L, 2018L, 
  2019L, 2020L, 2021L, 2018L, 2019L, 2020L, 2021L), Cost = c(NA, 
  100L, NA, NA, 99L, 45L, 34L, NA, 64L, 34L, NA, 34L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -12L))
  </code></pre>
  <p>The focus here is on the column &quot;Cost&quot; . If there is NA, in a first step, I use the most recent year with available data in the respective category.</p>
  <pre><code>Data %&gt;%
    group_by(`Category`, Year) %&gt;%
    dplyr:: mutate(Cost = na.locf(Cost))
  </code></pre>
  <p>The problem now is that for &quot;Name&quot; A, there is no value in the &quot;Year&quot; 2018. That's why I get an error. How do I need to adjust, the code, that then in a second step, if there is no data available from prior year for this respective &quot;Category&quot;, I use the data from the next available year. In this specific case it would be &quot;Year&quot; 2019 and the value 100.</p>
  <p>Thank you for your help in advance.</p>