r - 每天将 "data.frame"传输到 R 中的 "ts"

标签 r time-series

我有一个数据集“rates”如下:

       Date  Price
1 2012-11-01 6.2411
2 2012-11-02 6.2415
3 2012-11-05 6.2454
4 2012-11-06 6.2456
5 2012-11-07 6.2437
6 2012-11-08 6.2429

> class(rate)
[1] "data.frame"

并尝试使用 R 代码将此数据集转换为时间序列数据:
rate<-ts(data = rate, start =1, freq=1)
> class(rate)
[1] "mts"    "ts"     "matrix"

> head(rate)
     Date  Price
[1,] 15645 6.2411
[2,] 15646 6.2415
[3,] 15649 6.2454
[4,] 15650 6.2456
[5,] 15651 6.2437
[6,] 15652 6.2429

如您所见,日期变成了数字。因此我使用 as.date() 函数:
rate[,1] <- as.Date(rate[,1],origin = "1899-12-30")
> head(rate)
       Date  Price
[1,] -719162 6.2411
[2,] -718797 6.2415
[3,] -718432 6.2454
[4,] -718067 6.2456
[5,] -717701 6.2437
[6,] -717336 6.2429

有没有人可以帮我解决这个问题?谢谢你。

最佳答案

您的代码的问题在于,在将整个数据帧强制转换为时间序列矩阵后,您尝试将日期列转换为日期类型。这样做的正确方法是首先将“日期”转换为日期类型,根据起始年份(2012 年)的每日增量计算起始日期,然后使用该信息将“价格”列转换为时间序列。

# Here is your data in "dput" form
rate = structure(list(Date = c("2012-11-01", "2012-11-02", "2012-11-05", 
                           "2012-11-06", "2012-11-07", "2012-11-08"), 
                  Price = c(6.2411, 6.2415, 6.2454, 6.2456, 6.2437, 6.2429)), 
             .Names = c("Date", "Price"), class = "data.frame", row.names = c(NA, -6L))

# Convert Date column to type "Date"
rate$Date = as.Date(rate$Date, format = "%Y-%m-%d")

# Convert "11-01" to day of the year 
dayOfYear = as.numeric(format(rate[1,1], "%j"))

# Use 2012 and dayOfYear as starting date
rate_ts = ts(rate$Price, start = c(2012, dayOfYear), frequency = 365)

> class(rate_ts)
[1] "ts"

> rate_ts
Time Series:
Start = c(2012, 306) 
End = c(2012, 311) 
Frequency = 365 
[1] 6.2411 6.2415 6.2454 6.2456 6.2437 6.2429
在这里,"%j" 只是告诉 format.Date 函数将 Date (2012-11-01) 的第一个元素转换为一年中的第几天。
我还想指出,由于您的 ts 是每天,您应该使用 frequency = 365 而不是 frequency = 1
绘图
# Plot time series without x-axis
plot(rate_ts, ylab = "Price", xaxt = "n")

# Extract first and last date value of rate_ts
tsp = attributes(rate_ts)$tsp

# Plot x-axis
axis(1, at = seq(tsp[1], tsp[2], along = rate_ts), 
     labels = format(rate$Date, "%Y-%m-%d"))
最后一行允许您通过更改 format() 的第二个参数来根据需要格式化 x 轴。 at = 参数允许您指定刻度。
enter image description here
感谢 Jake Burkhead 在 this answer 中的绘图方法

关于r - 每天将 "data.frame"传输到 R 中的 "ts",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859009/

相关文章:

regex - 删除R中URL字符串的结尾

S4 类中的 R 公共(public)方法

r - 如何使用 R 计算字符串中的 CAPSLOCK

python - Plotly:使用 Python 在多行图中添加色阶

r - 在HTS R中创建分层数据结构,节点

R 中 xts 的回归

r - r 中的最佳簇数

python - 按月 reshape Pandas 数据框

R:如何在同一时间序列上绘制多个 ARIMA 预测

r - 饼图,其中标签显示在饼图内部,百分比显示在饼图外部