use tidyr::fill but with specific values for fill

Viewed 112

I am trying to figure out a functionality very similar to tidyr::fill but instead of using the next or previous entry seek to use a specific value.

To give an example

library(tibble)

xtest <- as.tibble(c(NA,NA, seq(10,70,10), NA, NA))
colnames(xtest)<- "data"
ytest <- tidyr::fill(xtest, 'data', .direction='down')
ytest <- tidyr::fill(ytest, 'data', .direction='up')
ytest

The tibble created is:

    data
   <dbl>
 1    10
 2    10
 3    10
 4    20
 5    30
 6    40
 7    50
 8    60
 9    70
10    70
11    70

What I would like to do is replace the first two NAs with 0 (instead of the 10s) and the last two NAs with 100 (instead of the 70s).

The .direction option comes close but uses the next or previous entry.

Is there an alternative to fill() that provides this capability?

1 Answers

You can use na.fill from the package zoo. You can set what you would like for the left, interior, and right of your data. You can also use extend rather than a value.

zoo::na.fill(xtest, c(0, "extend", 100))

       data
 [1,]     0
 [2,]     0
 [3,]    10
 [4,]    20
 [5,]    30
 [6,]    40
 [7,]    50
 [8,]    60
 [9,]    70
[10,]   100
[11,]   100
Related