change_*()
allows you to change the day, month, year, or date of a
Date
, POSIXct
, or
POSIXlt
object.
change_date(x, date)
change_day(x, day)
change_month(x, month)
change_year(x, year)
Other parsing/conversion functions:
convert_to_unit()
## Scalar example
change_day(as.Date("2021-01-01"), 15)
#> [1] "2021-01-15"
#> [1] "2021-01-15" # Expected
change_month(as.POSIXct("2021-01-01 12:00:00", tz = "UTC"), 12)
#> [1] "2021-12-01 12:00:00 UTC"
#> [1] "2021-12-01 12:00:00 UTC" # Expected
change_year(as.POSIXlt("2021-01-01 12:00:00", tz = "UTC"), 2022)
#> [1] "2022-01-01 12:00:00 UTC"
#> [1] "2022-01-01 12:00:00 UTC" # Expected
change_date(
x = as.POSIXlt("2021-01-01 12:00:00", tz = "UTC"),
date = as.Date("2000-01-01")
)
#> [1] "2000-01-01 12:00:00 UTC"
#> [1] "2000-01-01 12:00:00 UTC" # Expected
## Vector example
x <- as.Date(c("2021-01-01", "2021-01-01"))
change_day(x, 15)
#> [1] "2021-01-15" "2021-01-15"
#> [1] "2021-01-15" "2021-01-15" # Expected
x <- as.POSIXct(c("2021-01-01 12:00:00", "2021-01-01 12:00:00"), tz = "UTC")
change_month(x, 10:11)
#> [1] "2021-10-01 12:00:00 UTC" "2021-11-01 12:00:00 UTC"
#> [1] "2021-10-01 12:00:00 UTC" "2021-11-01 12:00:00 UTC" # Expected
x <- as.POSIXlt(c("2021-01-01 12:00:00", "2021-01-01 12:00:00"), tz = "UTC")
change_year(x, 2022)
#> [1] "2022-01-01 12:00:00 UTC" "2022-01-01 12:00:00 UTC"
#> [1] "2022-01-01 12:00:00 UTC" "2022-01-01 12:00:00 UTC" # Expected
x <- as.POSIXlt(c("2021-01-01 12:00:00", "2021-01-01 12:00:00"), tz = "UTC")
change_date(x, as.Date("2000-01-01"))
#> [1] "2000-01-01 12:00:00 UTC" "2000-01-01 12:00:00 UTC"
#> [1] "2000-01-01 12:00:00 UTC" "2000-01-01 12:00:00 UTC" # Expected