R:从csv中提取适当的时间日期

时间:2013-04-24 11:59:12

标签: r csv time-series text-parsing

我有一个带有一些时间序列数据的csv,其日期时间的格式如下:

mydata <- read.csv("mydata.csv")
> mode(mydata$t_5min[1])
[1] "numeric"

看起来R将其解释为一个因素,因为它无法理解格式:

mydata$t_5min[1]
[1] 1/3/2012 16:00
27698 Levels: 10/10/2012 10:00 10/10/2012 10:05 10/10/2012 10:10 10/10/2012 10:15 ... 9/6/2012 9:55

我尝试使用strptime,这对单个条目似乎没问题:

> strptime(x=mydata$t_5min[2],format="%d/%m/%Y %H:%M", tz="")
[1] "2012-04-01 06:10:00"
> mode(strptime(x=mydata$t_5min[2],format="%d/%m/%Y %H:%M", tz=""))
[1] "list"

但如果我尝试使用sapply,我会收到以下错误:

mydata$t_5min <- sapply(mydata$t_5min, strptime, format="%d/%m/%Y %H:%M", tz="")
Error in `$<-.data.frame`(`*tmp*`, "t_5min", value = list(sec = 0, min = 0L,  : 
replacement has 9000 rows, data has 1000

我尝试了timeDate库,结果略好一些:

> as.timeDate(mydata$t_5min[1])
GMT
[1] [2012-01-03]

但是,我需要精确度。但是,timeDate函数中的示例代码似乎不起作用(或者我使用它错了,但它有点简短):

as.timeDate(mydata$t_5min[2], units=c("min"))
Error in as.timeDate(mydata$t_5min[2], units = c("min")) : 
unused argument(s) (units = c("min"))

将此时间数据转换为R可以使用的内容的正确方法是什么?

以下是复制这些结果的一些数据:

t_5min,n,value
1/3/2012 16:00,16,48.125
1/3/2012 16:05,28,44.39285714
1/3/2012 16:10,29,37.44827586
1/3/2012 16:15,28,30.39285714
1/3/2012 16:20,28,23.67857143
1/3/2012 16:25,29,19.10344828
1/3/2012 16:30,28,16.35714286
1/3/2012 16:35,29,14.34482759
1/3/2012 16:40,28,11.71428571

2 个答案:

答案 0 :(得分:3)

您可以使用read.zoo以正确的格式直接读取数据:

library(zoo)
## you repalce text=... here by file = "mydata.csv"
read.zoo(text='
t_5min,n,value
1/3/2012 16:00,16,48.125
1/3/2012 16:05,28,44.39285714
1/3/2012 16:10,29,37.44827586
1/3/2012 16:15,28,30.39285714
1/3/2012 16:20,28,23.67857143
1/3/2012 16:25,29,19.10344828
1/3/2012 16:30,28,16.35714286
1/3/2012 16:35,29,14.34482759
1/3/2012 16:40,28,11.71428571',header=TRUE,format="%d/%m/%Y %H:%M", tz="",sep=',')


                    n    value
2012-03-01 16:00:00 16 48.12500
2012-03-01 16:05:00 28 44.39286
2012-03-01 16:10:00 29 37.44828
2012-03-01 16:15:00 28 30.39286
2012-03-01 16:20:00 28 23.67857
2012-03-01 16:25:00 29 19.10345
2012-03-01 16:30:00 28 16.35714
2012-03-01 16:35:00 29 14.34483
2012-03-01 16:40:00 28 11.71429

答案 1 :(得分:2)

试试这个:

> as.POSIXlt(as.character(df$t_5min), format="%d/%m/%Y %H:%M")
[1] "2012-03-01 16:00:00" "2012-03-01 16:05:00" "2012-03-01 16:10:00"
[4] "2012-03-01 16:15:00" "2012-03-01 16:20:00" "2012-03-01 16:25:00"
[7] "2012-03-01 16:30:00" "2012-03-01 16:35:00" "2012-03-01 16:40:00"