[R] write.table read.table with Dates

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Nov 10 15:51:08 CET 2005


On Thu, 10 Nov 2005, JeeBee wrote:

> I've found several similar issues with write.table/read.table
> with Dates on this list, but trying to follow this advice I still
> get an error.
>
> First, I read in data from several files, constructing several date/time
> columns using ISOdatetime
>
>> str(Tall$Begin)
> 'POSIXct', format: chr [1:40114] "2005-10-02 00:00:00" "2005-10-02
> 00:00:00" ...
>> length(Tall$Begin)
> [1] 40114
>> class(Tall$Begin)
> [1] "POSIXt"  "POSIXct"
>
> This looks good (time is not always 00:00:00 ...)
> This data came from several files, now I want to store the result I have
> in data.frame Tall and be able to retrieve this quickly some other time.
>
> This is what I do:
> write.table(Tall, file="somefile.csv", sep=",", qmethod="double",
> row.names=FALSE)
>
> Later, I do this to read the file again:
> fieldnames=c("Begin","test-a","test-b","Eind")
> T=read.table(file = "somefile.csv", col.names = fieldnames,
>  header = TRUE, sep = ",", quote="\"", fill=FALSE)

You can avoid all this trouble by using colClasses as documented on the 
help page.

> I understand T$Begin now is a factor. I tried to simply convert it
> again using (as I read on this mailinglist ...):
> Q = strptime(as.character(T$Begin),format="%Y-%m-%d %H:%M:%S")

Or just as.POSIXct(as.character(T$Begin))

> Q is looking good, though its length I don't understand .. is it a list or
> something? It seems there are 40114 values in there somewhere...

It is a list of length 9.  Try names(Q)

>> class(Q)
> [1] "POSIXt"  "POSIXlt"
>> length(Q)
> [1] 9
>> str(Q)
> 'POSIXlt', format: chr [1:40114] "2005-10-02 00:00:00" "2005-10-02 00:00:00" ...
>
> T$Begin = Q ### yields this error
> Error in "$<-.data.frame"(`*tmp*`, "Begin", value = list(sec = c(0, 0,  :
>        replacement has 9 rows, data has 40114
>
> Could somebody explain me how to convert the date column?
> Or perhaps there is an easier way?

You started with POSIXct, and you need to convert back to POSIXct
with as.POSIXct(Q).

Reading ?DateTimeClasses should explain to you what you are missing.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list