Skip to contents

To print a listing of all examples of a chapter, use ch6(). To run all the examples of ch6(), use example(ch6).

Usage

ch06()

ch6()

See also

toc

Other Chapters: ch01(), ch02(), ch03(), ch04(), ch05(), ch07(), ch08(), ch09(), ch10(), ch11(), ch12(), ch13(), ch14(), ch15(), ch16(), ch17(), ch18(), ch19(), ch20()

Examples

if (interactive()) {
# Chapter 6 - Going on a Date with R

# Working with Dates

xd <- as.Date("2012-07-27")
xd
str(xd)
weekdays(xd)
xd + 7
xd + 0:6
weekdays(xd + 0:6)

startDate <- as.Date("2012-01-01")
xm <- seq(startDate, by="2 months", length.out=6)
xm
 months(xm)
quarters(xm)

Sys.localeconv()

as.Date("27 July 2012", format="%d %B %Y")

as.Date("27/7/12", format="%d/%m/%y")

# Adding Time Information to Dates

apollo <- "July 20, 1969, 20:17:39"
apollo.fmt <- "%B %d, %Y, %H:%M:%S"
xct <- as.POSIXct(apollo, format=apollo.fmt, tz="UTC")
xct <- as.POSIXct(apollo, format=apollo.fmt)
xct

format(xct, "%d/%m/%y")
format(xct, "%S minutes past %I %p, on %d %B %Y")

# Performing Operations on Dates and Times

## Addition and subtraction

24*60*60
xct + 7*86400
xct + 3*60*60
xct - 7*86400
as.Date(xct) - 7

## Comparison of dates

Sys.time()
Sys.time() < xct

dec.start <- as.POSIXct("1950-01-01")
dec <- seq(dec.start, by="10 years", length.out=4)
dec
dec > xct

## Extraction

xlt <- as.POSIXlt(xct)
xlt
xlt$year
xlt$mon
unclass(xlt)









}