How to Describe the Center of Continuous Data in R
How to Search for Individual Words in R
How to Summarize Logical Vectors 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 Substitute Text in R
How to Store and Calculate Values in R
How to Change Values in a Vector in R
How to Use read.csv() to Import Data in R
How to Create Subgroups of Data in R
Advertisement

Inside Dummies.com