2014-12-02 60 views
3

我试图导入一个包含ISO8601时间戳值(例如2014-12-01T18:54:22.973 + 0000)的字段为Ts的csv文件。如何阅读具有时间戳字段的csv?

我已经看到了你可以指定类列:

kd <- read.csv("my.csv", colClasses=c("Ts"="?" )) 

但是,我无法找到如何声明时间戳字段。

问题:如何指定该字段是时间戳?

+0

您需要t o使用'setAs'来创建一个可以处理该colClass的函数。例如:http://stackoverflow.com/a/3611619/967840,http://stackoverflow.com/a/10823641/967840 – GSee 2014-12-02 20:45:00

回答

4

.csv文件直接转换为时间序列对象,则可以使用zoo包中的函数read.zoo()。这在内部调用read.table()(而不是read.csv),然后转换指定的时间索引列。见?read.zoovignette("zoo-read", package = "zoo")

带有时间标记像您的一个例子是:

csv <- 
"x,y,timestamp 
0,1,2014-12-01T18:54:22.973+0000 
1,2,2014-12-01T19:43:11.862+0000" 
read.zoo(text = csv, sep = ",", header = TRUE, index = "timestamp", 
    format = "%Y-%m-%dT%H:%M:%OS%z", tz = "GMT") 

这产生了zoo一系列POSIXct时间戳:

    x y 
2014-12-01 18:54:22 0 1 
2014-12-01 19:43:11 1 2 

(当然,text = csv将不得不被替换如file = "my.csv",如果您正在从磁盘读取.csv文件而不是从R中读取文本字符串)。

2

不知道的方式直接做在读,但作为一种解决方法(直到有人更了解答案),你可以做转换后记:如果你想读

kd <- read.csv("my.csv") 
% Assume that the timestamp column in the csv file has the header 'timestamp' 

kd$newtimestamp <- strptime(kd$timestamp,format="%FT%H:%M:%OS%z") 

% By default this will convert all times to your timezone 
% but you can control the conversion through the tx argument e.g. tx='GMT'