Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

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
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.