sunt
sunt

Reputation: 303

R: data-time objects in data frame

> my.lt <- strptime("2003-02-05 03:00:02", format="%Y-%m-%d %H:%M:%S")
> x <- data.frame(d=my.lt)
> class(x$d)
[1] "POSIXct" "POSIXt" 

I don't know why data.frame changed x$d from a POSIXlt object to a POSIXct one. Now if I do

> x$d = my.lt

Then I got what I want, but this is ugly. Can anybody tell me 1) Why this happened; and 2) How to initialize a data frame with one of its column being a POSIXlt in a neat way.

Thank you.

Upvotes: 1

Views: 2322

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

As it says in the 3rd paragraph of the Details section of ?data.frame:

‘data.frame’ converts each of its arguments to a data frame by calling ‘as.data.frame(optional=TRUE)’.

That means as.data.frame.POSIXlt is being called. It's defined as:

function (x, row.names = NULL, optional = FALSE, ...) 
{
    value <- as.data.frame.POSIXct(as.POSIXct(x), row.names, 
        optional, ...)
    if (!optional) 
        names(value) <- deparse(substitute(x))[[1L]]
    value
}

So that's why it happened. I can't think of a clean way to do it using the data.frame constructor, but here is a bit of a kludge:

x <- data.frame(d=as.data.frame.vector(my.lt))

This converts your POSIXlt object to a data.frame using the vector method. If you really want to confuse yourself later, you can also use the POSIXct method:

x <- data.frame(d=as.data.frame.POSIXct(my.lt))
str(x)
# 'data.frame':   1 obs. of  1 variable:
#  $ my.lt: POSIXlt, format: "2003-02-05 03:00:02"

Upvotes: 5

Related Questions