Try

  hf$hour   <- as.POSIXlt(hf$date)$hour
  hf$month <- as.POSIXlt(hf$date)$mon+1


To see why, use the man pages to study the structure of POSIXlt objects.  Try:

 tmp <- strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
 unclass(tmp)

For example:

 tmp <- strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
 foo <- data.frame(date=c(tmp,tmp+3600), x=1:2)
 foo
                 date x
1 2006-02-20 11:16:16 1
2 2006-02-20 12:16:16 2
 foo$hour <- as.POSIXlt(foo$date)$hour
 foo$mon <- as.POSIXlt(foo$date)$mon+1

 foo
                 date x hour mon
1 2006-02-20 11:16:16 1   11   2
2 2006-02-20 12:16:16 2   12   2



Just to be thorough, note:

 class(tmp)
[1] "POSIXt"  "POSIXlt"

 class(foo$date)
[1] "POSIXt"  "POSIXct"

So strptime() creates objects of class POSIXlt, which are silently converted to POSIXct when put in a dataframe.

Compare
   unclass(tmp)
   unclass(foo$date)

-Don

At 11:40 AM +0100 7/2/09, Tim Chatterton wrote:
I have a data frame (hf) that is all set up and the dates are working fine - however I need to extract the months and hours (2 separate columns) as numbers - however they are coming out as characters.

I have tried both the following:

hf50$hour=  hf50$date
hf50$hour=format(hf50["hour"],"%H")

and

hf$month <- as.POSIXct(strptime(hf$date, format = "%m"))

but they are still coming out as characters.

Any ideas please?
Thanks,
Tim.

______________________________________________
R-help@r-project.org mailing list
https://*stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


--
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to