首先,解決您的格式和使用包像xts
得到一個合適的時間序列對象:
# Read in the data. In the future, use `dput` or something else
# so that others can read in the data in a more convenient way
temp = read.table(header=TRUE, text=" V1 V2 V3
1 20100420 915 120
2 20100420 920 150
3 20100420 925 270
4 20100420 1530 281")
# Get your date object and format it to a date/time object
date = paste0(temp[[1]], apply(temp[2], 1, function(x) sprintf("%04.f", x)))
date = strptime(date, format="%Y%m%d%H%M")
# Extract just the values
values = temp[[3]]
# Load the xts package and convert your dataset
require(xts)
xts(values, order.by=date)
# [,1]
# 2010-04-20 09:15:00 120
# 2010-04-20 09:20:00 150
# 2010-04-20 09:25:00 270
# 2010-04-20 15:30:00 281
在日期轉換:
apply(temp[2], 1, ...)
去逐行對於臨時的第二列和將數字重新格式化爲四位數字。
- 然後,
paste0
將所有的日期 - 時間信息結合到單個向量。
- 最後,
strptime
將該字符向量轉換爲適當的日期時間對象。
更新
當然,如果你想只是一個普通data.frame
,你也可以這樣做,但我強烈建議,如果你想要做真正的時間序列分析使用類似zoo
或xts
。
下面是簡單的data.frame
步驟(在之前創建date
和values
對象之後)。
data.frame(V3 = values, row.names=date)
# V3
# 2010-04-20 09:15:00 120
# 2010-04-20 09:20:00 150
# 2010-04-20 09:25:00 270
# 2010-04-20 15:30:00 281
你有什麼試過的?這在R文檔和關於SO的不同問題上有很好的文檔記錄。 – A5C1D2H2I1M1N2O1R2T1 2012-07-30 05:57:33
爲了澄清,在原始數據中,什麼是'V3'? – A5C1D2H2I1M1N2O1R2T1 2012-07-30 06:15:25
它可能是股票的一些數據,前兩列是日期,最後一列可能是'open.price','close.price','volumn'等。 – PepsiCo 2012-07-30 06:21:57