format date as year in r

To format a date into year format in R, you can use the lubridate package to manipulate the date object and then use the format() function to specify the output as year only. Here's an example:

main.r
library(lubridate)

# create example date object
date <- ymd("20210105")

# format date as year only
year_only <- format(date, "%Y")

# output result
print(year_only) # "2021"
176 chars
11 lines

In the above code, we load the lubridate library, create an example date object using the ymd() function, and then use the format() function to specify that we want only the year portion of the date. The %Y format code specifies that we want a four-digit year. The resulting output is "2021".

gistlibby LogSnag