[R] write.table read.table with Dates

Gabor Grothendieck ggrothendieck at gmail.com
Thu Nov 10 15:32:26 CET 2005


On 11/10/05, JeeBee <JeeBee at troefpunt.nl> 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)
>
> 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")
>
> 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...
>
> > 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 are converting it to POSIXlt (which represents date/times as a 9
element structure) but its likely you really wanted to convert it to
POSIXct.

as.POSIXct(T$Begin)

Also, you might need to use the tz= argument depending on what result
you want.

See the Help Desk article in RNews 4/1 for more info.




More information about the R-help mailing list