I am trying to convert a sparse matrix to a time series object. The codes are following:
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
How can I convert a sparse matrix to a time series object?
Try converting the sparse matrix into a regular matrix first, with the knowledge that the ts
function interprets each column of the matrix as a separate time series:
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)
Output:
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
Note: This approach will consume a lot of memory if the sparse matrix is very large. In such cases, you will need to come up with an alternative strategy.