How to Extract Specific Elements from a Date in R - dummies

How to Extract Specific Elements from a Date in R

By Andrie de Vries, Joris Meys

Another thing you may want to do in R is to extract specific elements of the date, such as the day, month, or year. For example, scientists may want to compare the weather in a specific month (say, January) for many different years.

To do this, they first have to determine the month, by extracting the months from the datetime object.

An easy way to achieve this is to work with dates in the POSIXlt class, because this type of data is stored internally as a named list, which enables you to extract elements by name. To do this, first convert the Date class:

> xlt <- as.POSIXlt(xct)
> xlt
[1] "1969-07-20 20:17:39 UTC"

Next, use the $ operator to extract the different elements. For example, to get the year, use the following:

> xlt$year
[1] 69

And to get the month, use the following:

> xlt$mon
[1] 6

You can use the unclass() function to expose the internal structure of POSIXlt objects.

> unclass(xlt)

If you run this line of code, you’ll see that POSIXlt objects are really just named lists.