是否应该索引矩阵与xts对象一起使用?

时间:2013-02-20 03:06:47

标签: r xts

当我使用带有xts对象的索引矩阵时,我得到了令人惊讶的结果。见下文。

如果我将x强制转换为矩阵(不出所料),它会按预期工作。

感谢您的帮助。

> data(sample_matrix)
> x<- as.xts(sample_matrix)
> i<- matrix(1:4, 2, 2,  byrow=T )
> i
     [,1] [,2]
[1,]    1    2
[2,]    3    4
> head(x)
               Open     High      Low    Close
2007-01-02 50.03978 50.11778 49.95041 50.11778
2007-01-03 50.23050 50.42188 50.23050 50.39767
2007-01-04 50.42096 50.42096 50.26414 50.33236
2007-01-05 50.37347 50.37347 50.22103 50.33459
2007-01-06 50.24433 50.24433 50.11121 50.18112
2007-01-07 50.13211 50.21561 49.99185 49.99185
> x[i]<- NA
> head(x)
               Open     High      Low    Close
2007-01-02       NA 50.11778 49.95041 50.11778
2007-01-03       NA 50.42188 50.23050 50.39767
2007-01-04       NA 50.42096 50.26414 50.33236
2007-01-05       NA 50.37347 50.22103 50.33459
2007-01-06 50.24433 50.24433 50.11121 50.18112
2007-01-07 50.13211 50.21561 49.99185 49.99185

1 个答案:

答案 0 :(得分:3)

我有一个解决方法。而不是

x[i]<- NA

使用coredata:

> coredata(x)[i]<- NA
> head(x)
               Open     High      Low    Close
2007-01-02 50.03978       NA 49.95041 50.11778
2007-01-03 50.23050 50.42188 50.23050 50.39767
2007-01-04 50.42096 50.42096 50.26414       NA
2007-01-05 50.37347 50.37347 50.22103 50.33459
2007-01-06 50.24433 50.24433 50.11121 50.18112
2007-01-07 50.13211 50.21561 49.99185 49.99185

虽然我(初学者)似乎仍然认为xts在原始代码中做错了。