lubridate
lubridate copied to clipboard
`update()` function gives strange results when changing to the beginning of a leap year
When the update() function is used to change the year and yday it gives strange results when the actual year is a leap year.
What is the reason for this behavior?
x <- ymd("2009-09-02")
update(x, year = 2008, yday = 1)
[1] "2008-01-02" # should be "2008-01-01"
x <- ymd("2009-02-28")
update(x, year = 2008, yday = 1)
[1] "2008-01-01" # it works
x <- ymd("2009-03-01")
update(x, year = 2008, yday = 1)
[1] "2008-01-02" # doesn't work
year(x) <- 2008
yday(x) <- 1
x
[1] "2008-01-01" # as expected.
This seems to occur for all leap years, and is likely the purpose of this commented line: https://github.com/tidyverse/lubridate/blob/6f26b02de432cd9373ad4ce7766c36eacfc29918/src/update.cpp#L304
Looks like it was removed when resolving issue #567. The leap year code was added by @vspinu to resolve issue #319 of which this is issue looks identical to.
Perhaps there is a better way to solve #567?
@mitchelloharawild thanks for the refined trace. Looks like a regression indeed.
Works with clock's year-day type since, by design, you can't update multiple components at once
library(clock)
library(magrittr)
x <- year_month_day(2009, 9, 2) %>%
as_year_day()
x
#> <year_day<day>[1]>
#> [1] "2009-245"
x <- x %>%
set_year(2008) %>%
set_day(1)
x
#> <year_day<day>[1]>
#> [1] "2008-001"
as.Date(x)
#> [1] "2008-01-01"
Created on 2021-05-25 by the reprex package (v1.0.0)
Fixed in devel
library(lubridate, warn.conflicts = F)
#> Loading required package: timechange
x <- ymd("2009-09-02")
update(x, years = 2008, ydays = 1)
#> [1] "2008-01-01"
x <- ymd("2009-03-01")
update(x, years = 2008, ydays = 1)
#> [1] "2008-01-01"
Created on 2022-11-02 with reprex v2.0.2