How to change integer year to date year?

Viewed 36

In my dataset, class(data$Year) is integer. How can I change the year as Date year?

data$Year <- as.Date(as.character(data$Year), format = "%Y")
data$Year <- year(data$Year)

I tried this one but this time class(data$Year) gave numeric output. How can I transform it as Date object?

1 Answers

A "Date" class always is a full date, like "2022-04-29". A value "2022" of class "Date" is not possible.

You may conveniently convert it to, say, January first using ISOdate and as.Date. The latter is only important if you really want "Date" class and not "POSIXct".

x <- 2020:2022

ISOdate(x, 1, 1, 0) |> as.Date()
# [1] "2020-01-01" "2021-01-01" "2022-01-01"
Related