问题是 R 不允许用日期填充矩阵。两者都是"matrix"
类"Date"
。R 中 Date 对象的底层表示只是一个整数。因此,当您创建矩阵时y
,它会从x
(整数数组)获取基础数据,添加维度属性,然后创建类"matrix"
。
这个问题没有任何干净的方法。不过,您可以使用一些技巧。例如,您可以显式强制y
成为 class"Date"
以及"matrix"
with class(y)<-c("matrix","Date")
。 y
仍然会打印为日期向量,但您可以使用矩阵坐标对其进行操作:
> class(y)<-c("matrix","Date")
> head(y)
[1] "2013-09-02" "2013-09-09" "2013-09-16" "2013-09-23" "2013-09-30"
[6] "2013-10-07" "2013-09-03" "2013-09-10" "2013-09-17" "2013-09-24"
[11] "2013-10-01" "2013-10-08" "2013-09-04" "2013-09-11" "2013-09-18"
[16] "2013-09-25" "2013-10-02" "2013-10-09" "2013-09-05" "2013-09-12"
[21] "2013-09-19" "2013-09-26" "2013-10-03" "2013-10-10" "2013-09-06"
[26] "2013-09-13" "2013-09-20" "2013-09-27" "2013-10-04" "2013-10-11"
[31] "2013-09-07" "2013-09-14" "2013-09-21" "2013-09-28" "2013-10-05"
[36] "2013-10-12" "2013-09-08" "2013-09-15" "2013-09-22" "2013-09-29"
[41] "2013-10-06" "2013-10-13"
> y[1,]
[1] "2013-09-02" "2013-09-03" "2013-09-04" "2013-09-05" "2013-09-06"
[6] "2013-09-07" "2013-09-08"
> y[1,]<-y[1,]+1
> y[1,]
[1] "2013-09-03" "2013-09-04" "2013-09-05" "2013-09-06" "2013-09-07"
[6] "2013-09-08" "2013-09-09"
您还可以使用数据框而不是矩阵:
> y<-data.frame(y)
> y<-data.frame(lapply(y,function(x) {class(x)<-"Date";x}))
> head(y)
X1 X2 X3 X4 X5 X6 X7
1 2013-09-02 2013-09-03 2013-09-04 2013-09-05 2013-09-06 2013-09-07 2013-09-08
2 2013-09-09 2013-09-10 2013-09-11 2013-09-12 2013-09-13 2013-09-14 2013-09-15
3 2013-09-16 2013-09-17 2013-09-18 2013-09-19 2013-09-20 2013-09-21 2013-09-22
4 2013-09-23 2013-09-24 2013-09-25 2013-09-26 2013-09-27 2013-09-28 2013-09-29
5 2013-09-30 2013-10-01 2013-10-02 2013-10-03 2013-10-04 2013-10-05 2013-10-06
6 2013-10-07 2013-10-08 2013-10-09 2013-10-10 2013-10-11 2013-10-12 2013-10-13
第三种可能性是将元素保持为y
字符格式,然后as.Date
在需要时将它们转换为日期:
> y<-matrix(as.character(x),nrow=20,byrow=T)
> head(y)
[,1] [,2] [,3] [,4] [,5]
[1,] "2013-09-02" "2013-09-03" "2013-09-04" "2013-09-05" "2013-09-06"
[2,] "2013-09-09" "2013-09-10" "2013-09-11" "2013-09-12" "2013-09-13"
[3,] "2013-09-16" "2013-09-17" "2013-09-18" "2013-09-19" "2013-09-20"
[4,] "2013-09-23" "2013-09-24" "2013-09-25" "2013-09-26" "2013-09-27"
[5,] "2013-09-30" "2013-10-01" "2013-10-02" "2013-10-03" "2013-10-04"
[6,] "2013-10-07" "2013-10-08" "2013-10-09" "2013-10-10" "2013-10-11"
[,6] [,7]
[1,] "2013-09-07" "2013-09-08"
[2,] "2013-09-14" "2013-09-15"
[3,] "2013-09-21" "2013-09-22"
[4,] "2013-09-28" "2013-09-29"
[5,] "2013-10-05" "2013-10-06"
[6,] "2013-10-12" "2013-10-13"
> as.Date(y[1,])
[1] "2013-09-02" "2013-09-03" "2013-09-04" "2013-09-05" "2013-09-06"
[6] "2013-09-07" "2013-09-08"