Extracting Year & Month of zoo::yearmon Date in R (Example Code)

This tutorial illustrates how to return only the year and month from a zoo yearmon object in the R programming language.

Setting up the Example

install.packages("zoo")          # Install zoo package
library("zoo")                   # Load zoo
x <- as.yearmon(c("Dez 2018",    # Create yearmon vector
                  "Jan 2022",
                  "Sep 2020"),
                "%b %Y")
x                                # Printing yearmon vector to RStudio console
# [1] "Dez 2018" "Jan 2022" "Sep 2020"

Example: Applying year() & month() Functions of lubridate Package to Extract Years & Months from yearmon Object

install.packages("lubridate")    # Install & load lubridate
year(x)                          # Extract years
# [1] 2018 2022 2020
month(x)                         # Extract months
# [1] 12  1  9

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed