r - Recursively fill dates in dplyr mutate - Stack Overflow

Suppose you haveaa <- tibble(date = ymd(c('20240101','20240102',NA, NA, NA)))Ho

Suppose you have

aa <- tibble(date = ymd(c('20240101','20240102',NA, NA, NA)))

How do you fill the NA values using the dplry mutate statement?

This does not work. It only fill the first NA value.

library(lubridate)
aa %>% 
  mutate(date = if_else(!is.na(date), date, dplyr::lag(date) + lubridate::days(1)))

Suppose you have

aa <- tibble(date = ymd(c('20240101','20240102',NA, NA, NA)))

How do you fill the NA values using the dplry mutate statement?

This does not work. It only fill the first NA value.

library(lubridate)
aa %>% 
  mutate(date = if_else(!is.na(date), date, dplyr::lag(date) + lubridate::days(1)))
Share Improve this question asked Nov 19, 2024 at 1:22 JFDJFD 3492 silver badges13 bronze badges 2
  • 1 Are the set dates guaranteed to be sequential and without gaps? Or is there a chance to encounter something like tibble(date = ymd(c('20240101','20240103','20240104', NA, NA, '20240110'))) ? – margusl Commented Nov 19, 2024 at 8:14
  • mutate(aa, date = seq.Date(first(date), first(date) + n() - 1, 1)) might be the easiest. – Friede Commented Nov 19, 2024 at 9:56
Add a comment  | 

2 Answers 2

Reset to default 2

Here's one way:

aa |>
  group_by(grp = cumsum(!is.na(date))) |>
  mutate(
    date = first(date) + row_number() - 1
  ) |>
  ungroup() |>
  select(-grp)
# # A tibble: 5 × 1
#   date      
#   <date>    
# 1 2024-01-01
# 2 2024-01-02
# 3 2024-01-03
# 4 2024-01-04
# 5 2024-01-05

We can use accumulate (or Reduce from base R) to iterate over date with the anonymous function shown. Here y is the current date and x is the previous value of the function. coalesce returns its first non-NA argument.

library(purrr)
aa %>%
  mutate(date = accumulate(date, \(x, y) coalesce(y, x + 1)))

Other approaches are possible if we can make additional assumptions. If we knew that the dates always increase by 1, i.e. no gaps, then we can find the index, i, of the first non-NA date and use that:

aa %>% {
  i <- which.min(is.na(.$date))
  mutate(., date = date[i] + row_number() - i)
}

If, in addition, we knew that the first date is not NA then i must be 1 so it simplifies to

aa %>%
  mutate(date = first(date) + row_number() - 1)

Note

The input used:

library(dplyr)
library(lubridate)

aa <- tibble(date = ymd(c('20240101','20240102',NA, NA, NA)))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745587311a4634621.html

相关推荐

  • r - Recursively fill dates in dplyr mutate - Stack Overflow

    Suppose you haveaa <- tibble(date = ymd(c('20240101','20240102',NA, NA, NA)))Ho

    9小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信