如何将稀疏矩阵转换为时间序列对象?

问题描述 投票:0回答:1

我正在尝试将稀疏矩阵转换为时间序列对象。代码如下:

i<−c(1,3,8,4,2,7,6,9,1,4,10,5,11,2,12)
j<−c(2,5,3,8,6,2,4,2,4,5,2,7,3,2,1)
x<−rpois(15,5)

M4<−sparseMatrix(i,j,x=x)

timeseries <- ts(M4)
timeseries

Object of class "ts"
Error in getDataPart(object) : 
  Data part is undefined for general S4 object

如何将稀疏矩阵转换为时间序列对象?

r statistics time-series sparse-matrix
1个回答
0
投票

首先尝试将稀疏矩阵转换为规则矩阵,并了解

ts
函数将矩阵的每一列解释为单独的时间序列:

library(Matrix)

set.seed(1)  # Set seed so deterministic results (at least on your machine).
i <- c(1, 3, 8, 4, 2, 7, 6, 9, 1, 4, 10, 5, 11, 2, 12)
j <- c(2, 5, 3, 8, 6, 2, 4, 2, 4, 5, 2, 7, 3, 2, 1)
x <- rpois(15, 5)
M4 <- sparseMatrix(i, j, x = x)
M4_regular_matrix <- as(M4, "matrix")
timeseries <- ts(M4_regular_matrix)
print(timeseries)

输出:

Time Series:
Start = 1 
End = 12 
Frequency = 1 
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
 1    0    4    0    6    0    0    0    0
 2    0    4    0    0    0    3    0    0
 3    0    0    0    0    4    0    0    0
 4    0    0    0    0    2    0    0    8
 5    0    0    0    0    0    0    3    0
 6    0    0    0    9    0    0    0    0
 7    0    8    0    0    0    0    0    0

注意: 如果稀疏矩阵非常大,这种方法会消耗大量内存。在这种情况下,您需要想出替代策略。

© www.soinside.com 2019 - 2024. All rights reserved.