Domanda

I'm starting to get a handle on how base R handles dates/times, but still have some uncertainty.

Using the following data set (exert from meteorological data), I was able to convert to POSIXct and POSIXlt using the as.character() function. The Date.Time is provided in the format yymmddhhmm.

Date.Time <- c(1107151300, 1107151400, 1107151500, 1107151600, 1107151700, 1107151800)
WindSpd <-   c(11.8, 14.5, 14.9, 14.1, 15.2, 17.1)

##Using as.character()##
#Note POSIXlt this time
w <- data.frame(Date.Time, WindSpd)
w$Date.Time <- as.POSIXlt(as.character(w$Date.Time), format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
w

#Now POSIXct
x <- data.frame(Date.Time, WindSpd)
x$Date.Time <- as.POSIXct(as.character(x$Date.Time), format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
x

However, it seems silly to convert integers to characters in the sake of converting to a date. When I try to convert the integers directly, I get all NA values.

##Trying to coerce the intergers##
#note POSIXlt this time
y <- data.frame(Date.Time, WindSpd)
y$Date.Time <- as.POSIXlt(y$Date.Time, format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
y

#note POSIXct this time
z <- data.frame(Date.Time, WindSpd)
z$Date.Time <- as.POSIXct(z$Date.Time, format = '%y%m%d%H%M', 
origin = '2011-07-15 13:00:00')
z

Obviously this isn't a crucial problem, as I've found a working solution. I would like to know anyways, as I'm trying to become a betteR codeR. What am I doing wrong in converting the integers to the R date classes? Also, are their benefits associated with POSIXlt vs POSIXct? According to the help article, it sounds like the only difference is how they are stored?

È stato utile?

Soluzione

There is an as.POSIXct.numeric method:

 > methods(as.POSIXct)
[1] as.POSIXct.date    as.POSIXct.Date    as.POSIXct.dates   as.POSIXct.default
[5] as.POSIXct.numeric as.POSIXct.POSIXlt

It uses numeric input as the number of seconds offset from the origin.

> as.POSIXct(1107151300, origin = '2011-07-15 13:00:00')
[1] "2046-08-14 19:01:40 PDT"
> as.POSIXct('1107151300', format = '%y%m%d%H%M', 
                          origin = '2011-07-15 13:00:00')
[1] "2011-07-15 13:00:00 PDT"

So, yes, you do need to use as.character.

Altri suggerimenti

Try removing the format spec (I believe it is only needed for character input):

zz <- as.POSIXct(Date.Time, origin = '2011-07-15 13:00:00')

It will work if you supply Date.Time as time in actual seconds from '2011-07-15 13:00:00' with the correct time zone

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top