0

There is a dataframe in the fPortfolio package called SPISECTOR.RET. I want my dataframe [df] to have the same format (global environment) as the dataframe [SPISECTOR.RET]. My df is currently a data.frame of 6 obs. of 3 variables. I want it in values as a timeSeries with a description of Formal Class timeSeries. I have dput for df attached below.

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

Below is what I tried to do by changing the date. however an error occured: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'))

dput(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"
))
Brian D
  • 79
  • 7

2 Answers2

2

You may have mixed up colnames for rownames. It looks like the dates are in "day-month-year" format as well. This should work:

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

mrhellmann
  • 5,069
  • 11
  • 38
0

You can use :

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213