Q:

Nearest non-NA value

I have a dataframe test
> test
   foo  bar  baz  timestamp
1    1 <NA>    a 1552157998
2    1 <NA> <NA> 1552161596
3    1 stop <NA> 1552165194
4    1 <NA>    b 1552168795
5    1 <NA>    a 1552170839
6    1 <NA> <NA> 1552157998
7    1 stop <NA> 1552161596
8    1 <NA>    a 1552165194
9    1 <NA>    b 1552168795
10   1 <NA> <NA> 1552170839

My goal is to find, for each instance of stop, the nearest non-NA value in each direction (based on timestamp), which would produce a table such like this:
> output
  rownum pre post
1      3   a    b
2      7   a    a

Is there a known way to do this with zoo and na.locf() ?
Any suggestions would be appreciated
dput(test)
structure(list(foo = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), bar = c(NA, 
NA, "stop", NA, NA, NA, "stop", NA, NA, NA), baz = c("a", NA, 
NA, "b", "a", NA, NA, "a", "b", NA), timestamp = c(1552157998.427, 
1552161596.004, 1552165194.255, 1552168794.918, 1552170839.363, 
1552157998.427, 1552161596.004, 1552165194.255, 1552168794.918, 
1552170839.363)), row.names = c(NA, -10L), class = "data.frame")

A:

I'll use magrittr solely for organizing the code. This can be translated just as easily to non-magrittr, dplyr, or data.table with minimal effort.
library(magrittr)
test %>%
  .[ order(.$timestamp), ] %>%
  transform(.,
            rownum = seq_len(nrow(.)),
            pre = zoo::na.locf0(baz),
            post = zoo::na.locf0(baz, fromLast = TRUE)) %>%
  subset(., bar == "stop") %>%
  .[, c("rownum", "pre", "post")]
#   rownum pre post
# 7      4   a    a
# 3      5   a    a

(This is different than the expected output, possibly because that's a mistake?)
You can see a little bit better what this is doing by looking at it before subset:
test %>%
  .[ order(.$timestamp), ] %>%
  transform(.,
            rownum = seq_len(nrow(.)),
            pre = zoo::na.locf0(baz),
            post = zoo::na.locf0(baz, fromLast = TRUE))
#    foo  bar  baz  timestamp rownum pre post
# 1    1 <NA>    a 1552157998      1   a    a
# 6    1 <NA> <NA> 1552157998      2   a    a
# 2    1 <NA> <NA> 1552161596      3   a    a
# 7    1 stop <NA> 1552161596      4   a    a
# 3    1 stop <NA> 1552165194      5   a    a
# 8    1 <NA>    a 1552165194      6   a    a
# 4    1 <NA>    b 1552168795      7   b    b
# 9    1 <NA>    b 1552168795      8   b    b
# 5    1 <NA>    a 1552170839      9   a    a
# 10   1 <NA> <NA> 1552170839     10   a <NA>

