2

几天来我一直在尝试解决这个问题,并且似乎很难在 R 中进行简单的日期列转换。

我需要先格式化日期和时间,然后才能使用 to.period 命令。我想格式化 mydata$Time 列,并将整个系列转换为 4 小时 OHLC 条。

下面是代码输入;

> mydata = read.csv("AUDJPY.csv")
> colnames(mydata) <- c("Pair","Time","Bid","Ask")
> head(mydata)
     Pair                  Time    Bid    Ask
1 AUD/JPY 20140501 00:00:00.301 94.874 94.893
2 AUD/JPY 20140501 00:00:00.312 94.876 94.895
3 AUD/JPY 20140501 00:00:00.316 94.876 94.882
4 AUD/JPY 20140501 00:00:00.317 94.877 94.884
5 AUD/JPY 20140501 00:00:00.403 94.877 94.885
6 AUD/JPY 20140501 00:00:00.420 94.877 94.887
> mydata$Time <- strptime(as.character(mydata$Time),"%Y%m%d_%H:%M:%S.%f")
> head(mydata)
     Pair Time    Bid    Ask
1 AUD/JPY <NA> 94.874 94.893
2 AUD/JPY <NA> 94.876 94.895
3 AUD/JPY <NA> 94.876 94.882
4 AUD/JPY <NA> 94.877 94.884
5 AUD/JPY <NA> 94.877 94.885
6 AUD/JPY <NA> 94.877 94.887
> class(mydata$Time)
[1] "POSIXlt" "POSIXt" 
> 

请帮忙!

4

1 回答 1

4

对于带小数的秒,您要使用“%OS”而不是“%S”。后者忽略了所有的值。如果你的格式有空格,你可以在格式字符串中包含一个空格。

观察

x<-c("20140501 00:00:00.301","20140501 00:00:00.420")

a<-strptime(x,"%Y%m%d %H:%M:%OS");
a
# [1] "2014-05-01 00:00:00 EDT" "2014-05-01 00:00:00 EDT"
a$sec
# [1] 0.301 0.420

虽然 R 在显示日期类的值时默认不显示小数默认值,但您可以看到它们存储在对象本身中。

于 2014-06-25T03:55:56.617 回答