'Fill in missing dates between two sequential dates in R [duplicate]
I'm working with a data set that has a date column in which the date is only recorded when it changes, meaning that any NAs are assumed to be equal to the most recently recorded date. I want to fill in missing dates based on that logic. Here's an example of what the data might look like:
| Date | Value |
|---|---|
| 10/2/2015 | A1 |
| NA | A2 |
| NA | A3 |
| NA | A4 |
| 10/3/2015 | B1 |
| NA | B2 |
| NA | B3 |
And here's the desired result:
| Date | Value |
|---|---|
| 10/2/2015 | A1 |
| 10/2/2015 | A2 |
| 10/2/2015 | A3 |
| 10/2/2015 | A4 |
| 10/3/2015 | B1 |
| 10/3/2015 | B2 |
| 10/3/2015 | B3 |
Thanks!
Solution 1:[1]
You can use tidyr:
df %>%
tidyr::fill(Date)
or
tidyr::fill(df, Date)
This gives us:
# A tibble: 7 × 2
Date Value
<chr> <chr>
1 10/2/2015 A1
2 10/2/2015 A2
3 10/2/2015 A3
4 10/2/2015 A4
5 10/3/2015 B1
6 10/3/2015 B2
7 10/3/2015 B3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt |
