title: creating a variable including the lag and lead of a date-time variable
body: <p>I have a dataset that somehow is similar to the following example. I am trying to create a variable the same as the &quot;expected&quot; variable. That is if the date_time is &quot;2020-01-02 12:00&quot;, create a variable including the lag, lead, and the level values of date_time.</p>
  <p>Thank you in advance.</p>
  <pre class="lang-r prettyprint-override"><code>    df &lt;- tibble(
               date_time = c(&quot;2020-01-01 10:00&quot;,&quot;2020-01-01 11:00&quot;,&quot;2020-01-01 12:00&quot;,&quot;2020-01-01 13:00&quot;,&quot;2020-01-01 14:00&quot;,&quot;2020-01-02 10:00&quot;,&quot;2020-01-02 11:00&quot;,&quot;2020-01-02 12:00&quot;,&quot;2020-01-03 10:00&quot;,&quot;2020-01-03 11:00&quot;), 
               
               date = c(&quot;2020-01-01&quot;,&quot;2020-01-01&quot;,&quot;2020-01-01&quot;,&quot;2020-01-01&quot;,&quot;2020-01-01&quot;,&quot;2020-01-02&quot;,&quot;2020-01-02&quot;,&quot;2020-01-02&quot;,&quot;2020-01-03&quot;,&quot;2020-01-03&quot;),
                 x= seq.default(1,5.5,.5),
  date_time_NA = c(NA,&quot;2020-01-01 11:00&quot;,NA,NA,NA,NA,NA,&quot;2020-01-02 12:00&quot;,NA,NA),
              expected = c(&quot;2020-01-01 10:00&quot;,&quot;2020-01-01 11:00&quot;,&quot;2020-01-01 12:00&quot;,NA,NA,NA,&quot;2020-01-02 11:00&quot;,&quot;2020-01-02 12:00&quot;,&quot;2020-01-03 10:00&quot;,NA) 
               )
  df
  
  </code></pre>
  <h2>NEW EXAMPLE</h2>
  <p>I changed the example above. So I am trying to tell R to find where date_time_NA is not missing and then create a variable including the lag, lead, and the level values of date_time (similar to expected).</p>
  <h2>UPDATE: another solution</h2>
  <p>I came up with a solution using the codes kindly shared by @akrun. It might not be a very smart solution; however, I found it intuitive.
  The main idea is to use ifelse to find the locations where the date_time_NA is not missing. Then we can use row_number() again and add 1 so it can find the lead and deduct 1, so it can find the lag location and replace them with the values of date_time.</p>
  <pre class="lang-r prettyprint-override"><code>df %&gt;%
   mutate(na_row = ifelse(!is.na(date_time_NA),row_number(),NA),
         
           row_level_lag = ifelse(row_number() %in% c(na_row), date_time,NA), 
         
           row_level_now = ifelse(row_number() %in% c(na_row + 1), date_time,NA),
         
           row_level_lead = ifelse(row_number() %in% c(na_row - 1), date_time,NA),
         
           date_time_expected = glue(&quot;{row_level_lag} {row_level_now} {row_level_lead}&quot;), 
         
           date_time_expected = stringr::str_replace_all(string = date_time_expected,pattern = &quot;NA&quot;,replacement = &quot;&quot;)) 
  
  </code></pre>