-1

Trying to use tidyr::fill() to fill in the blanks in the inception_date and expiry_date fields (filling in a downward direction) in a test data set:

enter image description here

Having trouble. If I run, for example:

library(dplyr)
library(tidyr)

test <- test %>% 
  mutate(new_inception_date = fill(inception_date, .direction = "down"))

I get an error message

no applicable method for 'fill' applied to an object of class "Date"

Does fill() not work with date fields? Is there a workaround?

Thank you.

zephryl
  • 14,633
  • 3
  • 11
  • 30
Alan
  • 619
  • 6
  • 19
  • 5
    `fill()` takes the entire dataframe as its first argument. So don’t use it inside `mutate()`; instead try `test %>% fill(inception_date, expiry_date)`. – zephryl Jan 29 '23 at 15:04
  • 4
    For future reference, please provide your data in a copy-pasteable form using `dput()`, [not as an image](https://meta.stackoverflow.com/a/285557/17303805). See [How to make a great R reproducible example](https://stackoverflow.com/q/5963269/17303805) for more guidance. – zephryl Jan 29 '23 at 15:05

1 Answers1

0

As suggested, fill works on a frame at a time. From ?fill:

Usage:

     fill(data, ..., .direction = c("down", "up", "downup", "updown"))
     
Arguments:

    data: A data frame.

     ...: <'tidy-select'> Columns to fill.

.direction: Direction in which to fill missing values. Currently either
          "down" (the default), "up", "downup" (i.e. first down and
          then up) or "updown" (first up and then down).

Quick demo of its usage:

df <- data.frame(date = Sys.Date() + replace(1:8, c(1, 4, 7), NA))
df
#         date
# 1       <NA>
# 2 2023-02-04
# 3 2023-02-05
# 4       <NA>
# 5 2023-02-07
# 6 2023-02-08
# 7       <NA>
# 8 2023-02-10
df %>%
  fill(date)
#         date
# 1       <NA>
# 2 2023-02-04
# 3 2023-02-05
# 4 2023-02-05
# 5 2023-02-07
# 6 2023-02-08
# 7 2023-02-08
# 8 2023-02-10
r2evans
  • 141,215
  • 6
  • 77
  • 149