format variable as year in r

You can format a variable as year in R using the lubridate package. Here’s an example code block:

main.r
# Load the lubridate package
library(lubridate)

# Create a date variable
date <- as.Date("2022-06-30")

# Extract the year from the date variable and format it as a year
year <- paste0(year(date))

# Print the formatted year
print(year)
238 chars
12 lines

In this example, we first load the lubridate package. Then, we create a date variable using the as.Date() function. We then use the year() function from lubridate to extract the year from the date variable. Finally, we use the paste0() function to format the year as a string, and print it to the console using print().

gistlibby LogSnag