【问题标题】:How can I transpose a time series to a matrix without losing Time Series type?如何在不丢失时间序列类型的情况下将时间序列转置为矩阵?
【发布时间】:2021-01-21 11:52:27
【问题描述】:

我有一个时间序列对象,但我想以这样的方式转置它,以便获得一个包含一列的矩阵而不会丢失 TS 类型。

类似:

Time-Series[1:492 , 1] from 1976 to 2017

每次我试图操纵时间序列时,它都会失去TS“类型”,变成num

我该如何解决这个问题?

【问题讨论】:

  • 你能use dput提供一个时间序列的样本吗?

标签: r time time-series


【解决方案1】:

1) dim 假设您有一个如下所示的ts 系列,请尝试使用dim<- 设置其尺寸:

tt <- ts(1:10, start = 2000, freq = 4)
dim(tt) <- c(length(tt), 1)

dim(tt)
## [1] 10  1

class(tt)
## [1] "ts"

1a) 这也可以写成:

tt <- ts(1:10, start = 2000, freq = 4)
tt2 <- `dim<-`(tt, c(length(tt), 1))

dim(tt2)
## [1] 10  1

class(tt2)
## [1] "ts"

frequency(tt2)
## [1] 4

start(tt2)
## [1] 2000    1

2) cbind 另一种方法是使用cbind。请注意,它可能不会显示为 10x1,但它是内部的,可以使用 dim(...) 进行检查。

cbind(tt, tt)[, 1, drop = FALSE]

3) zoo 不幸的是,cbind(tt) 没有给出预期的 10x1 结果,但我们可以转换为 zoo,使用 cbind 并转换回来。同样,它不会显示为 10x1,但在内部它是 10x1,可以使用 dim(...) 进行检查。

library(zoo)
as.ts(cbind(as.zoo(tt)))

使用 zoo 的大多数操作比使用 ts 更直接,因此您可以交替使用 zoo 对象。

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多