更改 xts 的索引格式

Changing index format of xts

我有一个索引格式为 "%Y-%m-%d" 的 'xts' 对象,我想将索引格式更改为 "%Y-%m".

我的问题是 tformat(x) <- "%Y-%m" 仅在打印时间序列时更改格式,但我不想更改索引本身。

format(as.Date(index(x), "%Y-%m-%d"), "%Y-%m")只是简单地提取索引并将其作为字符串给出。

我怎样才能正确地做到这一点?

xts 对象的索引实际上存储为以数字表示的日期,无论您选择如何格式化它都不会改变。

例如,让我们采用以下对象:

library(xts)

x <- xts(1:12, seq(as.Date("2020-01-01"), by = "month", length.out = 12))

x
#>            [,1]
#> 2020-01-01    1
#> 2020-02-01    2
#> 2020-03-01    3
#> 2020-04-01    4
#> 2020-05-01    5
#> 2020-06-01    6
#> 2020-07-01    7
#> 2020-08-01    8
#> 2020-09-01    9
#> 2020-10-01   10
#> 2020-11-01   11
#> 2020-12-01   12

现在我们可以unclass x 看出它“真的”是一个具有某些属性的数组。其中之一是日期 "index",以数字格式存储:

unclass(x)
#>       [,1]
#>  [1,]    1
#>  [2,]    2
#>  [3,]    3
#>  [4,]    4
#>  [5,]    5
#>  [6,]    6
#>  [7,]    7
#>  [8,]    8
#>  [9,]    9
#> [10,]   10
#> [11,]   11
#> [12,]   12
#> attr(,"index")
#>  [1] 1577836800 1580515200 1583020800 1585699200 1588291200 1590969600
#>  [7] 1593561600 1596240000 1598918400 1601510400 1604188800 1606780800
#> attr(,"index")attr(,"tzone")
#> [1] "UTC"
#> attr(,"index")attr(,"tclass")
#> [1] "Date"

现在让我们更改格式:

tformat(x) <- "%Y-%m"

x
#>         [,1]
#> 2020-01    1
#> 2020-02    2
#> 2020-03    3
#> 2020-04    4
#> 2020-05    5
#> 2020-06    6
#> 2020-07    7
#> 2020-08    8
#> 2020-09    9
#> 2020-10   10
#> 2020-11   11
#> 2020-12   12

当我们再次 unclass 时,我们看到 "index" 属性没有改变,尽管格式已经改变:

unclass(x)
#>       [,1]
#>  [1,]    1
#>  [2,]    2
#>  [3,]    3
#>  [4,]    4
#>  [5,]    5
#>  [6,]    6
#>  [7,]    7
#>  [8,]    8
#>  [9,]    9
#> [10,]   10
#> [11,]   11
#> [12,]   12
#> attr(,"index")
#>  [1] 1577836800 1580515200 1583020800 1585699200 1588291200 1590969600
#>  [7] 1593561600 1596240000 1598918400 1601510400 1604188800 1606780800
#> attr(,"index")attr(,"tzone")
#> [1] "UTC"
#> attr(,"index")attr(,"tclass")
#> [1] "Date"
#> attr(,"index")attr(,"tformat")
#> [1] "%Y-%m"

所以当你说你想改变索引本身时,你的意思并不清楚。该索引必须在内部表示为 some 确切的日期时间,但它是打印的。按照您的方式更改打印格式确实没有问题。