使用tidyr::fill()填充空白日期

jvlzgdj9  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(119)

尝试使用tidyr::fill()填充测试数据集中inception_dateexpiry_date字段中的空白(向下填充):

有困难。比如说,如果我跑步:

library(dplyr)
library(tidyr)

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

我收到错误消息

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

fill()不能处理日期字段吗?是否有解决方法?
谢谢你。

6yjfywim

6yjfywim1#

如建议的那样,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).

快速演示其用法:

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

相关问题