0

包中有一个fPortfolio名为SPISECTOR.RET. 我希望我的数据框 [ df] 具有与数据框 [ ] 相同的格式 ( global environment) SPISECTOR.RET。我df目前 data.frame6 obs. of 3 variables. 我想把它values作为timeSeries一个描述Formal Class timeSeries。我在df下面附上了 dput。

library('fPortfolio')
data = SPISECTOR.RET
data(head)

以下是我试图通过更改日期来做的事情。但是发生了错误:Error in xts(df, as.Date(colnames(df), format = "%m/%d/%Y")) : NROW(x) must match length(order.by)

library(xts)
stocks <- xts(df, as.Date(colnames(df), format='%m/%d/%Y'))

输入(df):

structure(list(ACWI = c(10795L, 10763L, 10768L, 10907L, 10761L, 
10905L), GLD = c(4811L, 4819L, 4853L, 4899L, 4924L, 4882L), TLT = c(615.88, 
615.13, 614.5, 617.38, 619.63, 628.63)), class = "data.frame", row.names = c("09/12/2019", 
"10/12/2019", "11/12/2019", "12/12/2019", "13/12/2019", "16/12/2019"
))
4

2 回答 2

2

你可能搞混colnamesrownames。看起来日期也是“日-月-年”格式。这应该有效:

library(xts)

my_xts <- xts(my_df, 
              as.Date(rownames(my_df),
                      format = "%d/%m/%Y"))

 head(my_xts)

            ACWI  GLD    TLT
2019-12-09 10795 4811 615.88
2019-12-10 10763 4819 615.13
2019-12-11 10768 4853 614.50
2019-12-12 10907 4899 617.38
2019-12-13 10761 4924 619.63
2019-12-16 10905 4882 628.63

于 2020-12-28T12:48:39.570 回答
0

您可以使用 :

library(xts)
stocks <- xts(df, as.Date(rownames(df), '%d/%m/%Y'))

#            ACWI  GLD TLT
#2019-12-09 10795 4811 616
#2019-12-10 10763 4819 615
#2019-12-11 10768 4853 614
#2019-12-12 10907 4899 617
#2019-12-13 10761 4924 620
#2019-12-16 10905 4882 629
于 2020-12-28T12:47:44.373 回答