# [R] Plotting with dates on X axis

Jack Lewis jl7001 at axe.humboldt.edu
Fri Apr 7 19:31:45 CEST 2000

```Steve (and anyone who might be interested),

Here are four simple functions I use in R to create dates and chron objects
(assumes you have the "chron" library attached):

make.chron <- function(date, time, out = "day mon year") {
# Makes a "chron object" from a date (yymmdd) and military time
# Date and time can be character or numeric vectors
# out is the format for the date portion only
ymd2date(date, out = out) + mt2msm(time)/1440
}

ymd2date <- function(date, out = "day mon year") {
# Converts a numeric or character date (yymmdd) to a "dates" object
date <- zfill(date, 6) # pad to 6 characters with starting zeros
dates(date, format="ymd", out=out, origin=c(1,1,1960))
}

mt2msm <- function(time)
{
# Converts a military time to minutes since midnight
if(data.class(time) == "character")
time <- as.numeric(time)
min <- time %% 100
hour <- time %/% 100
60 * hour + min
}

zfill <- function(x, n) {
# fill with leading zeros to get an n-digit character string
nc <- nchar(x)
zeros <- paste(rep(0, n), collapse = "")
paste(substring(zeros, nchar(x) + 1, n), substring(x, 1, nchar(x)), sep
= "")
}

In addition, although data.frame() and as.data.frame() will not accept chron
objects, you can add chron objects to data frames as follows:

data\$chr _ chron.obj

where data is an existing data frame and chron.obj is an existing chron
object.

When you display the data frame, the chron object will display as a julian
integer, UNLESS you mask the function as.matrix.data.frame() with a copy
that has one change:

Change the following conditional statement:

if (length(levels(xj)) > 0 || !(is.numeric(xj) || is.complex(xj)))
non.numeric <- TRUE

to:

if (length(levels(xj)) > 0 || is.dates(xj) || !(is.numeric(xj) ||
is.complex(xj)))
non.numeric <- TRUE

With that, the chron object will appear formatted when the data frame is
displayed.

--
Jack Lewis                           Redwood Sciences Laboratory
707-825-2929 voice                   Pacific Southwest Research Station
707-825-2901 fax                     USDA Forest Service
jl7001 at axe.humboldt.edu              http://www.rsl.psw.fs.fed.us
jlewis01 at fs.fed.us (alternate)

--------------------------------------------
Thought must be divided against itself before it can come to any
knowledge of itself.                             (Aldous Huxley)

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```

More information about the R-help mailing list