Convert Vector of Years to Date Object in R (Example Code)
This tutorial demonstrates how to transform a vector of years to a Date object in the R programming language.
Construction of Example Data
x <- seq(2022, 2028) # Construct example vector x # Print example years # [1] 2022 2023 2024 2025 2026 2027 2028 |
x <- seq(2022, 2028) # Construct example vector x # Print example years # [1] 2022 2023 2024 2025 2026 2027 2028
Example: Converting Four Digit Year to Date Object
install.packages("lubridate") # Install & load lubridate package library("lubridate") |
install.packages("lubridate") # Install & load lubridate package library("lubridate")
ymd(x, truncated = 2L) # Applying ymd function # [1] "2022-01-01" "2023-01-01" "2024-01-01" "2025-01-01" "2026-01-01" "2027-01-01" "2028-01-01" |
ymd(x, truncated = 2L) # Applying ymd function # [1] "2022-01-01" "2023-01-01" "2024-01-01" "2025-01-01" "2026-01-01" "2027-01-01" "2028-01-01"
Further Resources
Here, you can find some additional resources on topics such as factors, data conversion, and dates.