I want to do exactly this: Specify custom Date format for colClasses argument in read.table/read.csv

My DateTime strings in the csv have the format "2010-08-18T09:50:00.000+02:00". The last part is the difference to GMT.

So I adapted the solution given in the question above:

> setClass("myDateTime")
[1] "myDateTime"
> setAs("character","myDateTime", function(from) as.POSIXlt(from, tz=paste("GMT", substr(from,24,24), substr(from,26,26), sep=""), format="%Y-%m-%dT%H:%M:%S") )

So far everything works fine:

> as("2010-08-18T09:50:00.000+02:00", "myDateTime")
[1] "2010-08-18 09:50:00 GMT+2"

But when trying to read in data from a csv-file there is an error:

> text <- "num;source;date1;date2
+ 1000000001;test;1985-11-17T00:00:00.000+01:00;1985-11-17T00:00:00.000+01:00
+ 1000000047;test;1971-03-07T00:00:00.000+01:00;1985-11-17T00:00:00.000+01:00
+ 1000000128;test;1967-11-02T00:00:00.000+01:00;1985-11-17T00:00:00.000+01:00"
> tab2 <- read.table(textConnection(text), sep=";", header=T, row.names=NULL, quote="", colClasses = c("numeric","character","myDateTime","myDateTime"), na.string=c(""))
Error in strptime(x, format, tz = tz) : invalid 'tz' value

I can't find out where the error comes from. Can you help me?

有帮助吗?

解决方案

tz must be of length 1.

Therefore

setAs("character","myDateTime", function(from){
  as.POSIXlt(from, 
     tz = paste("GMT", unique(substr(from,24,24)), 
                       unique(substr(from,26,26)), sep="",collapse=''), 
     format="%Y-%m-%dT%H:%M:%S")
 })

should work

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top