2

我有一个 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
4

2 回答 2

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
于 2013-04-24T12:13:18.530 回答
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"
于 2013-04-24T12:18:39.573 回答