Learn R Programming

Epi (version 0.6.2)

cal.yr: Functions to convert character, factor and various date objects into a number, and vice versa.

Description

Dates are converted to a numerical value, giving the calendar year as a fractional number. 1 January 1970 is converted to 1970.0, and other dates are converted by assuming that years are all 365.25 days long, so inaccuracies may arise, for example, 1 Jan 2000 is converted to 1999.999. Differences between converted values will be 1/365.25 of the difference between corresponding Date objects.

Usage

cal.yr(x, format)
  as.Date.cal.yr( x, ... )
  as.Date.numeric( x, ..., unit="d" )

Arguments

x
A factor or character vector, representing a date in format format, or an object of class Date, POSIXlt,
format
Format of the date values if x is factor or character
unit
Which units are the date measured in, "y" for years, "d" for days.
...
Arguments passed on from other methods.

Value

  • cal.yr returns a numerical vector of the same length as x, of class c("cal.yr","numeric"). as.Date.cal.yr and as.Date.numeric return Date objects.

See Also

DateTimeClasses, Date

Examples

Run this code
# Charcter vector of dates:
 birth <- c("14/07/1852","01/04/1954","10/06/1987","16/05/1990",
            "01/01/1996","01/01/1997","01/01/1998","01/01/1999")
 # Proper conversion to class "Date":
 birth.dat <- as.Date( birth, format="%d/%m/%Y" )
 # Converson of character to class "cal.yr"
 bt.yr <- cal.yr( birth, format="%d/%m/%Y" )
 # Back to class "Date":
 bt.dat <- as.Date( bt.yr )
 # Numerical calculation of days since 1.1.1970:
 days <- Days <- (bt.yr-1970)*365.25
 # Blunt assignment of class:
 class( Days ) <- "Date"
 # Then data.frame() to get readable output of results:
 data.frame( birth, birth.dat, bt.yr, bt.dat, days, Days, round(Days) )

Run the code above in your browser using DataLab