我就是想这样做:Specify custom Date format for colClasses argument in read.table/read.csv
我的 csv 中的日期时间字符串的格式为“2010-08-18T09:50:00.000+02:00”。最后一部分是与GMT的区别。
所以我调整了上面问题中给出的解决方案:
> 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") )
到目前为止一切正常:
> as("2010-08-18T09:50:00.000+02:00", "myDateTime")
[1] "2010-08-18 09:50:00 GMT+2"
但是当尝试从 csv 文件读取数据时出现错误:
> 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
我无法找出错误来自哪里。你能帮我吗?
最佳答案
tz
长度必须为 1。
因此
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")
})
应该可以
关于r - 从 R 中的表读取自定义日期时间时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394175/