簡體   English   中英

使用R:如何創建帶日期的時間序列對象?

[英]Using R: How do I create a time-series object with dates?

我有一年一小時的一系列價值觀。 是否可以創建一個保留小時和年份值的時間序列對象?

我的代碼使用stockprices第1列中的值,但不使用日期:

stockprices.ts <- ts(stockprices[,1],start=1, freq=168)

您沒有提供數據樣本,但SO上有很多其他答案( 例如這里 ),涵蓋了這個問題。 我使用xts進行時間序列工作,盡管還有其他不錯的選擇。

假設您的數據是兩列,您可能通過read.table加載了一個數據框:

> stockprices <- data.frame(prices=c(1.1,2.2,3.3),
               timestamps=c('2011-01-05 11:00','2011-01-05 12:00','2011-01-05 13:00'))
> stockprices
  prices       timestamps
1    1.1 2011-01-05 11:00
2    2.2 2011-01-05 12:00
3    3.3 2011-01-05 13:00

你可以轉換為xts時間序列:

> require(xts)
> stockprices.ts <- xts(stockprices$prices, order.by=as.POSIXct(stockprices$timestamps))
> stockprices.ts
                    [,1]
2011-01-05 11:00:00  1.1
2011-01-05 12:00:00  2.2
2011-01-05 13:00:00  3.3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM