[R] POSIX problem
David Scott
d.scott at auckland.ac.nz
Tue May 31 14:26:40 CEST 2005
I am having trouble with creating a POSIXct object. If I create a variable
of class Date first out of the date part of my data, I am ok, but if I
just paste the date and time parts together and try and create the POSIXct
object, I have problems.
Here is a toy example created from the actual data which caused the
problem. I am using R 2.0.1 on Windows XP.
> # Data frame with dates and times, as character
> PeopleData.df
StartDate StartTime
1 29/10/2001 15:26
2 7/12/2001 10:32
3 16/11/2001 13:58
4 28/11/2001 14:00
5 2/11/2001 15:22
6 26/11/2001 11:15
> str(PeopleData.df)
`data.frame': 6 obs. of 2 variables:
$ StartDate: chr "29/10/2001" "7/12/2001" "16/11/2001" "28/11/2001" ...
$ StartTime: chr "15:26" "10:32" "13:58" "14:00" ...
> dput(PeopleData.df)
structure(list(StartDate = c("29/10/2001", "7/12/2001", "16/11/2001",
"28/11/2001", "2/11/2001", "26/11/2001"), StartTime = c("15:26",
"10:32", "13:58", "14:00", "15:22", "11:15")), .Names = c("StartDate",
"StartTime"), row.names = c("1", "2", "3", "4", "5", "6"), class =
"data.frame")
> BeginDate <- as.Date(PeopleData.df$StartDate,format="%d/%m/%Y")
> BeginDate
[1] "2001-10-29" "2001-12-07" "2001-11-16" "2001-11-28" "2001-11-02"
[6] "2001-11-26"
> # Create POSIXct date-time object without difficulty
> BeginTime <- as.POSIXct(format(paste(BeginDate,PeopleData.df$StartTime),
+ format="%Y/%m/%d %H:%M"))
> BeginTime
[1] "2001-10-29 15:26:00 New Zealand Standard Time"
[2] "2001-12-07 10:32:00 New Zealand Standard Time"
[3] "2001-11-16 13:58:00 New Zealand Standard Time"
[4] "2001-11-28 14:00:00 New Zealand Standard Time"
[5] "2001-11-02 15:22:00 New Zealand Standard Time"
[6] "2001-11-26 11:15:00 New Zealand Standard Time"
> # But not directly from the dates and times
> BeginTime <-
as.POSIXct(format(paste(PeopleData.df$StartDate,PeopleData.df$StartTime),
+ format="%d/%m/%Y %H:%M"))
> BeginTime
[1] "0029-10-20 New Zealand Standard Time"
[2] "0007-12-20 New Zealand Standard Time"
[3] "0016-11-20 New Zealand Standard Time"
[4] "0028-11-20 New Zealand Standard Time"
[5] "0002-11-20 New Zealand Standard Time"
[6] "0026-11-20 New Zealand Standard Time"
> # Format looks correct to me
> paste(PeopleData.df$StartDate,PeopleData.df$StartTime)
[1] "29/10/2001 15:26" "7/12/2001 10:32" "16/11/2001 13:58" "28/11/2001
14:00"
[5] "2/11/2001 15:22" "26/11/2001 11:15"
What I think might be causing the problem is the lack of a leading zero
for some of the days (as in 7/12/2001). This doesn't phase as.Date though.
David Scott
_________________________________________________________________
David Scott Department of Statistics, Tamaki Campus
The University of Auckland, PB 92019
Auckland NEW ZEALAND
Phone: +64 9 373 7599 ext 86830 Fax: +64 9 373 7000
Email: d.scott at auckland.ac.nz
Graduate Officer, Department of Statistics
More information about the R-help
mailing list