How to Track Data Correlations in R
How to Take Samples from Data in R
How to Use Regular Expressions in R

How to Extract Specific Elements from a Date in R

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Plot Summarized Data in a ggplot2 in R
How to Use Layers in ggplot2 in R
How to Add Color and a Key to Lattice Charts in R
How to Save Graphics to an Image File in R
How to Store and Calculate Values in R